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

Hybrid Search

The best of both.

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

Vectors understand meaning, but can miss exact words, like a brand or a model number. Keyword search nails exact words. Hybrid search runs both, and blends the scores.

  • Meaning
  • Exact words
  • Blend both

Keyword plus vectors

A bool query with two should clauses. A match on name finds exact words. A knn clause finds meaning. A document can score from either one, or both. Run it. Rain jackets first, then the next closest products by meaning.

hybrid.pypython
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer

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

q = "rain shell for storms"
resp = es.search(index="products", source=["name"], size=4, query={"bool": {"should": [
    {"match": {"name": q}},
    {"knn": {"field": "embedding", "k": 10, "num_candidates": 20,
             "query_vector": model.encode(q).tolist()}}]}})

for h in resp["hits"]["hits"]:
    print(round(h["_score"], 2), h["_source"]["name"])
Output
3.59 Storm Rain Jacket
3.56 Cloudburst Rain Jacket
3.55 Breeze Rain Jacket
0.71 Storm Dome Shelter
Also uses _load
vectors

Blending scores

Adding scores is simple, and boosts can weight each side. Reciprocal rank fusion, or RRF, blends by rank instead of score, and needs a paid license or a trial. Always test hybrid search on real questions.

keyvalue
bool shouldadd scores
boostweight a side
RRF retrieverrank fusion, licensed
Testreal questions

Summary

Hybrid search combines exact keyword matches with meaning from vectors. Next, using Elasticsearch for RAG.

Key takeaways
  • match + knn
  • bool should
  • RRF
Next up: RAG with Elasticsearch — answers from your data