Skip to content

Integration

Semantic menu search with Qdrant

Qdrant is a good fit for menu search when you want vector retrieval with rich filtering: by restaurant, delivery zone, price band or cuisine. This recipe stores a Latimal vector and a cuisine label on every dish, retrieves with filters, counts cuisine facets, and optionally reranks the top results with /search.

Prerequisites

  • A Latimal API key in LATIMAL_API_KEY. See Authentication.
  • A Qdrant instance (self-hosted or Qdrant Cloud). Facet counts need Qdrant 1.12 or later.
  • Python 3.9+ with requests and qdrant-client.
Shell
pip install requests qdrant-client

1. Enrich menu items with Latimal

This helper calls /embed/batch for vectors and /classify for a cuisine label, and stores a hash of the name so you can spot renamed items later.

Python
import hashlib
import os

import requests


class Latimal:
    """A thin client for the Latimal REST API, built on requests."""

    def __init__(self, api_key, base_url="https://dish-embed.latimal.com"):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers["X-API-Key"] = api_key

    def _post(self, path, payload):
        response = self.session.post(f"{self.base_url}{path}", json=payload, timeout=60)
        response.raise_for_status()
        return response.json()

    def embed(self, items):  # /embed: up to 512 items
        return self._post("/embed", {"items": items})["embeddings"]

    def embed_batch(self, items):  # /embed/batch: up to 5,000 items
        return self._post("/embed/batch", {"items": items})["embeddings"]

    def classify(self, items):  # /classify: up to 512 items
        return self._post("/classify", {"items": items})["results"]

    def search(self, query, corpus, top_k=10):  # /search: up to 512 corpus items
        return self._post("/search", {"query": query, "corpus": corpus, "top_k": top_k})

    def match(self, pairs):  # /match: up to 100 pairs
        return self._post("/match", {"pairs": pairs})


latimal = Latimal(os.environ["LATIMAL_API_KEY"])


def chunked(seq, size):
    for start in range(0, len(seq), size):
        yield seq[start:start + size]


def text_hash(name):
    return hashlib.sha256(name.encode("utf-8")).hexdigest()


def enrich(items):
    """Attach a Latimal vector, a cuisine label and a text hash to each item."""
    names = [item["name"] for item in items]
    vectors, labels = [], []
    for batch in chunked(names, 5000):  # /embed/batch: up to 5,000 items per call
        vectors.extend(latimal.embed_batch(batch))
    for batch in chunked(names, 512):  # /classify: up to 512 items per call
        labels.extend(latimal.classify(batch))
    for item, vector, label in zip(items, vectors, labels):
        item["embedding"] = vector
        item["text_hash"] = text_hash(item["name"])
        if label["cuisine"] != "uncertain":
            item["cuisine"] = label["cuisine"]
            item["cuisine_confidence"] = label["confidence"]
    return items


menu = [
    {"id": "athens-05-0003", "restaurant_id": "athens-05", "name": "Souvlaki Pita", "price": 4.50, "currency": "EUR"},
    {"id": "bangkok-18-0027", "restaurant_id": "bangkok-18", "name": "Khao Man Gai", "price": 2.00, "currency": "USD"},
    {"id": "singapore-01-0004", "restaurant_id": "singapore-01", "name": "Hainanese Chicken Rice", "price": 5.00, "currency": "USD"},
    {"id": "saopaulo-09-0015", "restaurant_id": "saopaulo-09", "name": "Pão de Queijo (6 un)", "price": 3.00, "currency": "USD"},
    {"id": "nairobi-02-0008", "restaurant_id": "nairobi-02", "name": "Nyama Choma Platter", "price": 11.50, "currency": "USD"},
    {"id": "dubai-09-0031", "restaurant_id": "dubai-09", "name": "Chicken Shawarma Wrap", "price": 7.50, "currency": "USD"},
]

items = enrich(menu)
dims = len(items[0]["embedding"])  # read the vector size from the response, never hardcode it

2. Create the collection

The vector size comes from the dims value you read in step 1. Keyword payload indexes on the fields you filter and facet by keep those queries fast.

Python
import uuid

from qdrant_client import QdrantClient, models

qdrant = QdrantClient(url=os.environ["QDRANT_URL"], api_key=os.environ.get("QDRANT_API_KEY"))
COLLECTION = "menu_items"


def ensure_collection(dims):
    if qdrant.collection_exists(COLLECTION):
        return
    qdrant.create_collection(
        collection_name=COLLECTION,
        vectors_config=models.VectorParams(size=dims, distance=models.Distance.COSINE),
    )
    for field in ("restaurant_id", "cuisine", "currency"):
        qdrant.create_payload_index(
            collection_name=COLLECTION,
            field_name=field,
            field_schema=models.PayloadSchemaType.KEYWORD,
        )


ensure_collection(dims)

3. Upsert the items

Qdrant point IDs must be unsigned integers or UUIDs. A UUIDv5 derived from your own item ID is stable, so re-upserting the same dish overwrites its point. Keep your original ID in the payload.

Python
def point_id(item_id):
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"menu-item:{item_id}"))


def to_point(item):
    payload = {key: value for key, value in item.items() if key != "embedding"}
    return models.PointStruct(id=point_id(item["id"]), vector=item["embedding"], payload=payload)


for batch in chunked(items, 500):
    qdrant.upsert(collection_name=COLLECTION, points=[to_point(item) for item in batch])

4. Search with filters and facets

Python
from functools import lru_cache


@lru_cache(maxsize=10_000)
def embed_query(query):
    # One /embed call per uncached query. Popular queries hit the cache.
    return tuple(latimal.embed([query])[0])


def build_filter(cuisine=None, restaurant_ids=None):
    must = []
    if cuisine:
        must.append(models.FieldCondition(key="cuisine", match=models.MatchValue(value=cuisine)))
    if restaurant_ids:
        must.append(models.FieldCondition(key="restaurant_id", match=models.MatchAny(any=list(restaurant_ids))))
    return models.Filter(must=must) if must else None


def search_menu(query, cuisine=None, restaurant_ids=None, limit=10):
    response = qdrant.query_points(
        collection_name=COLLECTION,
        query=list(embed_query(query)),
        query_filter=build_filter(cuisine, restaurant_ids),
        limit=limit,
        with_payload=True,
    )
    return [{"score": point.score, **point.payload} for point in response.points]


def cuisine_facets(restaurant_ids=None):
    response = qdrant.facet(
        collection_name=COLLECTION,
        key="cuisine",
        facet_filter=build_filter(restaurant_ids=restaurant_ids),
    )
    return {hit.value: hit.count for hit in response.hits}


# Restaurants that currently deliver to the user, from your own geo service
nearby = ["bangkok-18", "singapore-01", "dubai-09"]
for hit in search_menu("poached chicken with rice", restaurant_ids=nearby):
    print(f"{hit['name']} ({hit['price']} {hit['currency']}) score={hit['score']:.3f}")
print(cuisine_facets(nearby))

The MatchAny filter on restaurant_id is how you scope a search to the restaurants that deliver to a user right now. Qdrant applies payload filters during the vector search, so a narrow filter still returns a full page of results.

For the final ordering on a results page, pass your top candidates to Latimal /search. It applies a precision stage on top of vector similarity and drops weak tail matches.

Python
def search_and_rerank(query, candidates=50, top_k=10, **filters):
    hits = search_menu(query, limit=candidates, **filters)
    by_name = {}
    for hit in hits:
        by_name.setdefault(hit["name"], []).append(hit)
    if not by_name:
        return []
    ranked = latimal.search(query, corpus=list(by_name), top_k=top_k)
    return [hit for result in ranked["results"] for hit in by_name[result["text"]]]

That's one extra API call per search. Many teams use it on the main search page and skip it for autocomplete.

6. Keep the collection fresh when menus change

Only a name change needs Latimal. Price changes go through set_payload, and removed dishes are deleted by point ID.

Python
def sync_restaurant(restaurant_id, current_items):
    """Bring one restaurant's points in line with its current menu."""
    existing, offset = {}, None
    while True:
        points, offset = qdrant.scroll(
            collection_name=COLLECTION,
            scroll_filter=models.Filter(must=[
                models.FieldCondition(key="restaurant_id", match=models.MatchValue(value=restaurant_id)),
            ]),
            with_payload=["id", "text_hash"],
            limit=1000,
            offset=offset,
        )
        for point in points:
            existing[point.payload["id"]] = point.payload["text_hash"]
        if offset is None:
            break

    to_enrich = [item for item in current_items if existing.get(item["id"]) != text_hash(item["name"])]
    to_patch = [item for item in current_items if existing.get(item["id"]) == text_hash(item["name"])]

    if to_enrich:
        # Upsert replaces the whole point, so stale cuisine labels go too
        qdrant.upsert(collection_name=COLLECTION, points=[to_point(item) for item in enrich(to_enrich)])
    for item in to_patch:
        qdrant.set_payload(
            collection_name=COLLECTION,
            payload={"price": item["price"], "currency": item["currency"]},
            points=[point_id(item["id"])],
        )

    current_ids = {item["id"] for item in current_items}
    removed = [point_id(item_id) for item_id in existing if item_id not in current_ids]
    if removed:
        qdrant.delete(collection_name=COLLECTION, points_selector=models.PointIdsList(points=removed))

Run it from a POS webhook, a feed import, or a nightly job. A batch of up to 5,000 renamed items is still a single embedding call.