Integration
Semantic menu search with Elasticsearch and OpenSearch
On this page
If your menu search already runs on Elasticsearch or OpenSearch, you can keep BM25 for exact names and add Latimal vectors for everything keyword matching misses: "pollo asado" for grilled chicken, "something brothy" for ramen and pho, or a typo like "shawarama". This recipe stores a Latimal vector and a cuisine label on every item, then runs keyword and vector retrieval in one request.
The Elasticsearch steps come first. The OpenSearch section covers the parts that differ.
Prerequisites
- A Latimal API key in
LATIMAL_API_KEY. See Authentication. - Elasticsearch 8.x or 9.x, or OpenSearch 2.19 or later.
- Python 3.9+ with requests and your search client. Use the client major version that matches your cluster.
pip install requests elasticsearch
# or, for OpenSearch
pip install requests opensearch-py1. Enrich menu items with Latimal
Every recipe in this section starts with the same helper. It calls /embed/batch for vectors and /classify for a cuisine label, and stores a hash of the item name so you can tell later which items need re-enriching.
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": "lisbon-17-0004", "restaurant_id": "lisbon-17", "name": "Bacalhau à Brás", "price": 14.50, "currency": "EUR"},
{"id": "austin-03-0012", "restaurant_id": "austin-03", "name": "**NEW** Chicken Tinga Tacos (3 pcs)", "price": 13.00, "currency": "USD"},
{"id": "osaka-22-0008", "restaurant_id": "osaka-22", "name": "Tonkotsu Ramen", "price": 8.00, "currency": "USD"},
{"id": "dubai-09-0031", "restaurant_id": "dubai-09", "name": "Chicken Shawarma Wrap", "price": 7.50, "currency": "USD"},
{"id": "london-41-0002", "restaurant_id": "london-41", "name": "Pad Kra Pao Gai", "price": 14.00, "currency": "EUR"},
{"id": "cdmx-05-0019", "restaurant_id": "cdmx-05", "name": "Tacos al Pastor", "price": 5.00, "currency": "USD"},
]
items = enrich(menu)
dims = len(items[0]["embedding"]) # read the vector size from the response, never hardcode itSend raw names as they appear in your catalog. Latimal strips promo text, prices and serving sizes before encoding (see Built-in preprocessing), so **NEW** Chicken Tinga Tacos (3 pcs) is handled as chicken tinga tacos. Keep the original string in your index for display.
One HTTP request counts as one API call no matter how many items it carries, so a full catalog of 5,000 items costs one call for vectors plus ten for classification.
If you pass a dimension to /embed/batch, pass the same one to /embed for queries. Vectors of different sizes can't be compared.
2. Create the index
The vector field's size comes from the dims value you read in step 1, so the index always matches what Latimal returned.
from elasticsearch import Elasticsearch, helpers
es = Elasticsearch(os.environ["ES_URL"], api_key=os.environ["ES_API_KEY"])
INDEX = "menu-items"
def ensure_index(dims):
if es.indices.exists(index=INDEX):
return
es.indices.create(
index=INDEX,
mappings={
"properties": {
"restaurant_id": {"type": "keyword"},
"name": {"type": "text"},
"price": {"type": "float"},
"currency": {"type": "keyword"},
"cuisine": {"type": "keyword"},
"cuisine_confidence": {"type": "float"},
"text_hash": {"type": "keyword"},
"embedding": {
"type": "dense_vector",
"dims": dims,
"index": True,
"similarity": "cosine",
},
}
},
)
ensure_index(dims)Latimal vectors are L2-normalized, so dot_product similarity also works and is slightly cheaper. cosine is the safer default if any vectors in the field come from elsewhere.
3. Index the items
def to_action(item):
source = {key: value for key, value in item.items() if key != "id"}
return {"_index": INDEX, "_id": item["id"], "_source": source}
helpers.bulk(es, (to_action(item) for item in items))4. Run a hybrid search
Embed the query with Latimal, then send a BM25 match and a knn clause in the same request. Elasticsearch combines them as a disjunction and weights each side by its boost. The terms aggregation gives you cuisine facet counts for the sidebar.
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 search_menu(query, cuisine=None, restaurant_id=None, size=10):
filters = []
if cuisine:
filters.append({"term": {"cuisine": cuisine}})
if restaurant_id:
filters.append({"term": {"restaurant_id": restaurant_id}})
knn = {
"field": "embedding",
"query_vector": list(embed_query(query)),
"k": 50,
"num_candidates": 200,
"boost": 0.7,
}
if filters:
knn["filter"] = filters
resp = es.search(
index=INDEX,
query={
"bool": {
"must": {"match": {"name": {"query": query, "boost": 0.3}}},
"filter": filters,
}
},
knn=knn,
aggs={"cuisines": {"terms": {"field": "cuisine"}}},
size=size,
source_excludes=["embedding"],
)
hits = [{"id": hit["_id"], "score": hit["_score"], **hit["_source"]} for hit in resp["hits"]["hits"]]
facets = {bucket["key"]: bucket["doc_count"] for bucket in resp["aggregations"]["cuisines"]["buckets"]}
return hits, facets
hits, facets = search_menu("something brothy and warming")
for hit in hits:
print(f"{hit['name']} ({hit['price']} {hit['currency']}) score={hit['score']:.3f}")
print(facets)The filters go in both clauses. Inside knn, the filter is applied while candidates are gathered, so you still get k results for a narrow cuisine or a single restaurant.
BM25 scores are unbounded while kNN scores sit between 0 and 1, so the 0.3 / 0.7 split is a starting point. Tune it on a sample of your real queries. Exact-name lookups ("tacos al pastor") lean on BM25, while descriptive or misspelled queries lean on the vector side.
If your Elastic subscription includes retrievers with reciprocal rank fusion, you can swap the boosts for an rrf retriever that wraps a standard retriever and a knn retriever. Rank fusion ignores raw scores, so there's nothing to tune between the two sides. Check the Elastic subscription page for which tiers include it.
5. Keep the index fresh when menus change
Menus change all the time: new dishes, renamed items, price updates. Only a name change needs Latimal. A price change is a partial update, and a removed item is a delete.
def sync_restaurant(restaurant_id, current_items):
"""Bring one restaurant's documents in line with its current menu."""
existing = {
hit["_id"]: hit["_source"]["text_hash"]
for hit in helpers.scan(
es,
index=INDEX,
query={"query": {"term": {"restaurant_id": restaurant_id}}, "_source": ["text_hash"]},
)
}
to_enrich, to_patch = [], []
for item in current_items:
if existing.get(item["id"]) == text_hash(item["name"]):
to_patch.append(item) # same name: no Latimal call needed
else:
to_enrich.append(item) # new or renamed: re-embed and re-classify
current_ids = {item["id"] for item in current_items}
actions = [to_action(item) for item in enrich(to_enrich)] if to_enrich else []
actions += [
{"_op_type": "update", "_index": INDEX, "_id": item["id"],
"doc": {"price": item["price"], "currency": item["currency"]}}
for item in to_patch
]
actions += [
{"_op_type": "delete", "_index": INDEX, "_id": doc_id}
for doc_id in existing if doc_id not in current_ids
]
if actions:
helpers.bulk(es, actions)Run it from whatever already tells you a menu changed: a POS webhook, a partner feed import, or a nightly job. A full re-index uses the same enrich call, so rebuilding a large catalog stays cheap in API calls.
OpenSearch
The Latimal side is identical. The differences are the vector field type, a search pipeline for score normalization, and the hybrid query.
Create the index
from opensearchpy import OpenSearch, helpers
client = OpenSearch(
hosts=[os.environ["OPENSEARCH_URL"]],
http_auth=(os.environ["OPENSEARCH_USER"], os.environ["OPENSEARCH_PASSWORD"]),
)
INDEX = "menu-items"
def ensure_index(dims):
if client.indices.exists(index=INDEX):
return
client.indices.create(
index=INDEX,
body={
"settings": {"index": {"knn": True}},
"mappings": {
"properties": {
"restaurant_id": {"type": "keyword"},
"name": {"type": "text"},
"price": {"type": "float"},
"currency": {"type": "keyword"},
"cuisine": {"type": "keyword"},
"cuisine_confidence": {"type": "float"},
"text_hash": {"type": "keyword"},
"embedding": {
"type": "knn_vector",
"dimension": dims,
"method": {"name": "hnsw", "engine": "faiss", "space_type": "cosinesimil"},
},
}
},
},
)
ensure_index(len(items[0]["embedding"]))
helpers.bulk(client, (to_action(item) for item in items))The faiss engine supports cosinesimil from OpenSearch 2.19. On older clusters, use "engine": "lucene" with the same space type.
Create a normalization pipeline
BM25 and kNN scores live on different scales, so OpenSearch normalizes them in a search pipeline before combining. The weights follow the order of the sub-queries in the hybrid query below.
client.transport.perform_request(
"PUT",
"/_search/pipeline/menu-hybrid",
body={
"description": "Combine BM25 and Latimal vector scores for menu search",
"phase_results_processors": [
{
"normalization-processor": {
"normalization": {"technique": "min_max"},
"combination": {
"technique": "arithmetic_mean",
"parameters": {"weights": [0.3, 0.7]},
},
}
}
],
},
)Search
def search_menu(query, cuisine=None, size=10):
filters = [{"term": {"cuisine": cuisine}}] if cuisine else []
knn = {"vector": list(embed_query(query)), "k": 50}
if filters:
knn["filter"] = {"bool": {"filter": filters}}
resp = client.search(
index=INDEX,
params={"search_pipeline": "menu-hybrid"},
body={
"size": size,
"_source": {"excludes": ["embedding"]},
"query": {
"hybrid": {
"queries": [
{"bool": {"must": {"match": {"name": query}}, "filter": filters}},
{"knn": {"embedding": knn}},
]
}
},
"aggs": {"cuisines": {"terms": {"field": "cuisine"}}},
},
)
return resp["hits"]["hits"], resp["aggregations"]["cuisines"]["buckets"]The hybrid query and normalization processor ship with the neural search plugin, which is part of the default OpenSearch distribution. The sync_restaurant function from step 5 works unchanged with opensearchpy.helpers.
Related
- POST /embed and POST /embed/batch for vectors
- POST /classify for cuisine labels
- POST /search if you'd rather let Latimal rank a menu directly
- Search integration guide
- Benchmarks
- Aggregator search use case
- All integrations