AI Hints
Home›Elasticsearch Tutorial›RAG, Ingest Pipelines and Runtime Fields
Elasticsearch · Lesson 103 of 120

RAG with Elasticsearch

Answers from your data.

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

A shopper asks a question, not a search. Which jacket should I take for heavy rain? RAG retrieves the best products from Elasticsearch, and an AI model writes the answer from them.

  • A question
  • Retrieve products
  • AI writes the answer

Retrieve, then generate

First, kNN finds the three closest products. We turn them into a short context, one line per product. Then Gemini answers, using only those products. Run it. A short answer, grounded in Trailhead's real catalog.

rag.pypython
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer

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

q = "Which jacket should I take for heavy rain?"
resp = es.search(index="products", size=3, knn={"field": "embedding",
    "query_vector": model.encode(q).tolist(), "k": 3, "num_candidates": 20})
docs = [h["_source"] for h in resp["hits"]["hits"]]
context = "\n".join(f"{d['name']} ${d['price']}: {d['description']}" for d in docs)

prompt = f"Answer in two sentences, using only these products:\n{context}\n\nQ: {q}"
client = genai.Client()
answer = client.models.generate_content(
    model="gemini-flash-lite-latest", contents=prompt)
print(answer.text)
Output
The Cloudburst Rain Jacket is an ultralight option designed specifically to keep out
wind and rain. Alternatively, the Breeze Rain Jacket provides waterproof protection
ideal for cold mornings and windy ridges.
Also uses _load
vectors

RAG tips

Retrieval quality decides answer quality, so hybrid search helps. Keep the context short and relevant. Tell the model to use only the context. And show the sources, so shoppers can click through.

keyvalue
Retrievalhybrid is best
Contextshort, relevant
Promptuse only the context
Sourceslink the products

Summary

RAG retrieves from Elasticsearch, then an AI model writes an answer from those results. Next, cleaning data as it arrives, with ingest pipelines.

Key takeaways
  • Retrieve
  • Generate
  • Grounded
Next up: Ingest Pipelines — clean data on the way in