0

I have a mapping in my index that looks like this:

"document_vectors": {
        "type": "nested",
        "properties": {
          "doc_vector": {
            "type": "dense_vector",
            "dims": 768
          }
        }
      }

This represents an array of vectors that are associated with a particular document in my index. I want to query the cosine similarity across this array of vectors like this:

{
    'size': results_size,
    'query': {
        "nested": {
            "path": "document_vectors",
            "score_mode": "max",
            "query": {
                "script_score": {
                    "script": {
                        "source": "document_vectors.vector.size() == 0 ? 0 : cosineSimilarity(params.query_vector, document_vectors.vector)",
                        "params": {"query_vector": query_vector}
                    }
                }
            }
        }
    }

I am getting the following error when attampting this query (other queries on this index are working, but when I try this particular query I get the error):

RequestError(400, 'illegal_argument_exception', 'Required [query]')

I am not sure how to interpret the error- am I missing a "query" field somewhere? I adapted the query/mapping from this Stackoverflow post if that helps.

zcleghern
  • 827
  • 7
  • 21

1 Answers1

1

I had the same problem. It seems that "script_score" requires a "query" field inside of it.

So I added:

"query": {
          "match_all": {}
        }

above the "script" field and that seemed to work fine. I was going off of https://opensearch.org/docs/latest/search-plugins/knn/knn-score-script/ for reference.

Here's my overall query structure:

myscript = #<code to make the 'painless' script>

query = {
    "size": 5,
    "query": {
      "script_score": {
        "query": {
          "match_all": {}
        },
        "script": myscript 
      }
    }
    
}
 response = os.search(
     body = query,
     index = index_name
 )

Hope that helps

sharperpn
  • 11
  • 2