Opensearch scoring script with bool filter java

I have the following example from Opensearch documentation

InlineScript inlineScript = new InlineScript.Builder()
        .source("knn_score")
        .lang("knn")
        .params(Map.of(
                "field", JsonData.of("my_vector"),
                "query_value", JsonData.of(List.of(1.5, 5.5, 4.5, 6.4)),
                "space_type", JsonData.of("cosinesimil")
                ))
        .build();
Query query = new Query.Builder()
        .scriptScore(new ScriptScoreQuery.Builder()
            .query(new Query.Builder()
                .matchAll(new MatchAllQuery.Builder().build())
                .build())
            .script(new Script.Builder()
                .inline(inlineScript)
                .build())
            .build())
        .build();
SearchRequest searchRequest = new SearchRequest.Builder()
        .index(index)
        .query(query)
        .build();
SearchResponse<JsonNode> searchResponse = client.search(searchRequest, JsonNode.class);

I would like to do something similar, but instead of a matchAll query, I would like to use a BoolQuery. This is a sample BoolQuery:

      BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

      BoolQueryBuilder innerBoolQuery = QueryBuilders.boolQuery();

      innerBoolQuery.must(QueryBuilders.rangeQuery("price").gte(200).lte(350));

      boolQuery.filter(innerBoolQuery);

I want to do something like this, but have been unsuccessful:

Query query = new Query.Builder()
        .scriptScore(new ScriptScoreQuery.Builder()
            .query(boolQuery) ---> Compilation error.
            .script(new Script.Builder()
                .inline(inlineScript)
                .build())
            .build())
        .build();

An example of how I want my actual query to look like:

GET /my_index/_search
{
  "query": {
    "script_score": {
      "query": {
        "bool": {
          "filter": {
            "bool": {
              "must": [
                {
                  "range": {
                    "price": {
                      "gte": 200,
                      "lte": 350
                    }
                  }
                }
              ]
            }
          }
        }
      },
      "script": {
        "source": "knn_score",
        "lang": "knn",
        "params": {
          "field": "my_vector",
          "query_value": [1.5, 5.5, 4.5, 6.4],
          "space_type": "cosinesimil"
        }
      }
    }
  }
}

I am using the opensearch-java client. Kindly help.

Have you looked at opensearch-java? The latest release, 2.6, has support for knn query types.

The above code is using opensearch-java client. Fixed the description.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.