knn search query using python and elasticsearch

Viewed 487

I try to do this query with elasticsearch python client :

curl -X GET "localhost:9200/articles/_knn_search" -H 'Content-Type: application/json' -d '
{
  "knn": {
    "field": "title_vector",
    "query_vector": [-0.01807806, 0.024579186,...],
    "k": 10,
    "num_candidates": 100
  },
  "_source": ["title", "category"]
}
'

If anyone can help me with thanks.

EDIT : with elasticsearch python client > 8.0 there is a new function named knn_search so we can run knn_search very easy:

query = {
    "field": "title_vector",
    "query_vector": [-0.01807806, 0.024579186,...],
    "k": 10,
    "num_candidates": 100
}
es = Elasticsearch(request_timeout=600, hosts='http://localhost:9200')
res = es.knn_search(index="index_name", knn=query, source=["filed1", "field2"])
0 Answers
Related