AI Hints
Home›Elasticsearch Tutorial›Scan, FastAPI and a Search Service
Elasticsearch · Lesson 96 of 120

Practice: Python Search Service

Filters and facets.

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

Let's grow the API into a real search service. Search words, an optional brand filter, and brand facets with counts, all in one request.

  • Search words
  • Brand filter
  • Facets

Search with filters and facets

Post filter adds the brand only when one is passed, so the facet counts stay complete. The brand aggregation gives those counts. Run it. Summit products for the word warm, with counts for every brand.

service.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()

@app.get("/search")
def search(q: str, brand: str | None = None):
    resp = es.search(index="products", size=3, source=["name"],
        query={"match": {"description": q}},
        post_filter={"term": {"brand": brand}} if brand else None,
        aggs={"brands": {"terms": {"field": "brand", "size": 3}}})
    hits = [h["_source"]["name"] for h in resp["hits"]["hits"]]
    buckets = resp["aggregations"]["brands"]["buckets"]
    return {"hits": hits, "brands": {b["key"]: b["doc_count"] for b in buckets}}

client = TestClient(app)
print(client.get("/search", params={"q": "warm", "brand": "Summit"}).json())
Output
{'hits': ['Rechargeable 600 Headlamp', 'Dynamic 60m Climbing Rope', 'Camp Synthetic
Sleeping Bag'], 'brands': {'Summit': 5, 'Ridgeline': 3, 'NorthPeak': 2}}
Also uses _load
catalog

Where to go next

Add pagination with from and size, or search after. Add sorting options. Add highlighting for snippets. And cache popular searches. You now have a real search service.

keyvalue
Pagingfrom / search_after
Sortingprice, rating
Highlightssnippets
Cachepopular searches

Summary

You built a Python search service with filters and facets. Next, a new kind of search, by meaning.

Key takeaways
  • Filters
  • Facets
  • FastAPI
Next up: Keyword vs Semantic Search — words versus meaning