KnnQuery in java client

I am trying to execute a KnnQuery (Knn query | Elasticsearch Guide [8.13] | Elastic) in my java application

(So not the knn search: k-nearest neighbor (kNN) search | Elasticsearch Guide [8.13] | Elastic).

When you use knn in a query, you can't set parameter k since the size parameter is used.

But, the Java client with version 8.13 requires the k parameter: (co.elastic.clients.util.MissingRequiredPropertyException: Missing required property 'KnnQuery.k' ):

So my problem is kind of a deadlock. Elasticsearch doesn't support the k parameter when knn is used in a query, but the java client requires the k parameter.

So anyone else having this issue?

1 Like

It's a bug. Could you open an issue in GitHub - elastic/elasticsearch-java: Official Elasticsearch Java Client?

There's no workaround when using knn as a query vs the top level knn request.

1 Like

Thanks for the report. We fixed the issue in the Elasticsearch specification and now need to generate a new Java client.

I previously thought there was an existing workaround by setting the new values explicitly, but that does not work so I removed them from this post.

Sorry for the hassle.

How to set k to size?
if I set any value for k, the elastic will give error on

    "root_cause": [
      {
        "type": "x_content_parse_exception",
        "reason": "[15:23] [knn] unknown field [k]"
      }
    ],

@WEI_GUO Hello, can you please share the code you used to set k?

@BenTrent tells me that the knn query does not allow k to be set at all in knn queries (while it works in the top level knn objects). So you have to wait for the next Java client, sorry. The good news is that the specification was fixed.