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.
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 Elasticsearchfrom sentence_transformers import SentenceTransformeres = Elasticsearch("http://localhost:9200")model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")from google import genaiq = "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.
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.