elastic / elasticsearch-java

Official Elasticsearch Java Client
Apache License 2.0
409 stars 239 forks source link

How to deal with knnQuery in nestedQuery? #875

Closed Manjiz closed 2 weeks ago

Manjiz commented 2 weeks ago
{
  "query": {
    "nested": {
      "path": "semantic_text.inference.chunks",
      "query": {
        "knn": {
          "field": "semantic_text.inference.chunks.embeddings",
          "k": 5,
          "num_candidates": 10,
          "query_vector_builder": {
            "text_embedding": {
              "model_id": "clip-vit-b-32-multilingual-v1",
              "model_text": "some search text"
            }
          }
        }
      }
    }
  }
}

The second parameter of QueryBuilders.nestedQuery(..) needs to be QueryBuilder. But I can't find any kNN-like builder in QueryBuilders.

l-trotta commented 2 weeks ago

Hello! Which version of the client are you using? It could be that knn query wasn't added yet. In latest versions (>=8.13.3) you can translate the query like this:

esClient.search(s -> s
        .query(q -> q
            .nested(n -> n
                .path("semantic_text.inference.chunks")
                .query(qq -> qq
                    .knn(k -> k
                        ...
                        ))))
    ,Object.class);

The only problem with this is that the knn query builder is missing the k field, which was added to the elasticsearch server in 8.15.0, but will only be available in the next client patch, releasing soon.

Manjiz commented 2 weeks ago

@l-trotta It's 7.x. I included an older version by mistake. Thanks for your time.