AI Hints
Home›Elasticsearch Tutorial›kNN, Filters and Hybrid Search
Elasticsearch · Lesson 100 of 120

kNN Search

Nearest neighbours.

⏱ 2 min read▶ Video at 1:34:02🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Now the products have vectors. To search by meaning, we embed the shopper's words, then ask for the products whose vectors are closest. That's k nearest neighbours, or k NN.

  • Embed the query
  • Find closest vectors
  • kNN

Search by meaning

We embed the shopper's question with the same model. The knn option takes the vector field, the query vector, and k, the number of results. Num candidates sets how many to check on each shard. Run it. Three rain jackets, even though no words match.

knn.pypython
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer

es = Elasticsearch("http://localhost:9200")
model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

q = "something to keep me dry in a storm"
resp = es.search(index="products", source=["name"], knn={
    "field": "embedding",
    "query_vector": model.encode(q).tolist(),
    "k": 3, "num_candidates": 20})

for h in resp["hits"]["hits"]:
    print(round(h["_score"], 3), h["_source"]["name"])
Output
0.811 Breeze Rain Jacket
0.811 Storm Rain Jacket
0.785 Cloudburst Rain Jacket
Also uses _load
vectors

kNN settings

K is how many results you want back. Num candidates is how many to look at per shard, more is more accurate but slower. The search is approximate, using a graph called HNSW. And scores are similarity, higher is closer.

keyvalue
kresults wanted
num_candidatesaccuracy vs speed
IndexHNSW graph
_scoresimilarity

Summary

kNN search embeds the query, and finds the products with the closest vectors. Next, combining kNN with filters.

Key takeaways
  • knn
  • k
  • num_candidates
Next up: Filtered kNN — meaning plus rules