Aproximate Nearest Neighbours python with leastic 8.8

Hello All
I am using elastic version 8.8.1.
The API for ANN has changed and I managed to index but not to query content.

from datetime import datetime
b_index = 'shot_index'
dim = 1280
response = es.indices.create(
"mappings": {
"properties": {
"my_vector": {
"type": "dense_vector",
"dims": dim, # adjust this according to your vector dimensions
"index": True,
"similarity": "l2_norm" # choose the similarity metric
"timestamp": {
"type": "date"

Index a document with a vector

doc = {
'my_vector': fvecs[0], # your vector goes here
'timestamp': datetime.now(),
resp = es.index(index=b_index, id=1, document=doc)

That works but the query didn't due to the change in the API in 8.8.
How can I query?
body = {
"size": 10,
"query": {
"knn": {
"image_vector": {
"vector": fvecs[0],
"k": 5
"_source": ["name", "file_type"]

response = es.search(index=b_index, body=body)

Result in:

BadRequestError: BadRequestError(400, 'illegal_argument_exception', '[knn] queries cannot be provided directly, use the [knn] body parameter instead')

I tried various methods and checked the docs but I didn't see any python related updates.

Heya @Ran_Dubin !

knn is its own top level object and isn't nested under query. For the python client it should look something like

es.search(index= b_index, knn={"query_vector": fvecs[0], "k":5, "num_candidates": 50, "field": image_vector}, size=10)

Thank you for the reply. Is there a blog/ python example for version 8.8?

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