OpenSearch: use vector search in combination with should

168 views Asked by At

Suppose my index has:

  • A vector field called "text_encoded"
  • A field called "field1", that can contain one or more of the following classes: "A", "B", "C" as list (ex. "field1" : ["A"], or "field1" : ["A", "C"])

I would like to write an OpenSearch query that can:

  • select the samples with field1 classes containing either "A" OR "C"
  • return similarity scores only

If I use the "should" instruction, it returns relevance scores instead.

1

There are 1 answers

0
fucalost On BEST ANSWER

The below query enables you to achieve this. Note that it uses Exact kNN with Scoring Script, as opposed to approximate kNN.

First, the script_score.query clause fetches a subset of documents where field1 is either "A" or "B". Then, the script_score.script clause performs kNN on the aforementioned set.

{
  "query": {
    "script_score": {
      "query": {
        "bool": {
          "should": [
            { "match": { "field1": "A" }},
            { "match": { "field1": "B" }}
          ]
        }
      },
      "script": {
        "source": "knn_score",
        "lang": "knn",
        "params": {
          "field": "text_encoded",
          "query_value": [0.1, 0.2, 0.3],
          "space_type": "cosinesimil"
        }
      }
    }
  }
}

Good luck!