opensearchvector-databasesemantic-search

OpenSearch: use vector search in combination with should


Suppose my index has:

I would like to write an OpenSearch query that can:

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


Solution

  • 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!