Integration
Food-aware menu search with Algolia and Latimal
On this page
Algolia gives you fast keyword search, typo tolerance and a polished front-end toolkit. Latimal adds food knowledge on top: dish names across languages and spellings, cuisine labels, and descriptive queries like "something light for lunch". The two work well together. Algolia stays your search engine and UI, and Latimal feeds it better data and a sharper final ranking.
This recipe covers three additions, in the order most teams ship them:
- Food-aware reranking of Algolia's top hits with /search.
- Cuisine facets on every record from /classify.
- Cross-language dish synonyms confirmed with /match.
Prerequisites
- A Latimal API key in
LATIMAL_API_KEY. See Authentication. - An Algolia application with an index of menu items, plus an app ID and an API key with write access (
ALGOLIA_APP_ID,ALGOLIA_WRITE_KEY). - Python 3.9+ with requests and the Algolia Python client v4.
pip install requests numpy "algoliasearch>=4,<5"Setup
import hashlib
import os
from algoliasearch.search.client import SearchClientSync
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"])
algolia = SearchClientSync(os.environ["ALGOLIA_APP_ID"], os.environ["ALGOLIA_WRITE_KEY"])
INDEX = "menu_items"
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()
menu = [
{"objectID": "tokyo-11-0003", "restaurant_id": "tokyo-11", "name": "Oyakodon", "price": 5.00, "currency": "USD"},
{"objectID": "berlin-02-0017", "restaurant_id": "berlin-02", "name": "Chicken and Egg Rice Bowl", "price": 12.90, "currency": "EUR"},
{"objectID": "london-41-0002", "restaurant_id": "london-41", "name": "Pad Kra Pao Gai", "price": 14.00, "currency": "EUR"},
{"objectID": "sydney-08-0021", "restaurant_id": "sydney-08", "name": "Thai Holy Basil Chicken", "price": 14.50, "currency": "USD"},
{"objectID": "toronto-14-0009", "restaurant_id": "toronto-14", "name": "Shakshuka", "price": 12.50, "currency": "USD"},
{"objectID": "cdmx-05-0019", "restaurant_id": "cdmx-05", "name": "Tacos al Pastor", "price": 5.00, "currency": "USD"},
]1. Rerank Algolia's top hits
Ask Algolia for a generous first page, then let Latimal reorder it. Algolia does the fast recall over your full catalog, and Latimal decides which of those candidates best answer the query. You can run this in your backend search endpoint, between Algolia and your app.
def search_menu(query, restaurant_id=None, candidates=50, top_k=20):
params = {"query": query, "hitsPerPage": candidates}
if restaurant_id:
params["filters"] = f"restaurant_id:{restaurant_id}"
res = algolia.search_single_index(index_name=INDEX, search_params=params)
hits = [hit.to_dict() for hit in res.hits]
if not hits:
return []
by_name = {}
for hit in hits:
by_name.setdefault(hit["name"], []).append(hit)
ranked = latimal.search(query, corpus=list(by_name), top_k=top_k)
ordered = []
for result in ranked["results"]:
for hit in by_name[result["text"]]:
ordered.append({**hit, "latimal_score": result["score"]})
return ordered/search drops weak tail results, so the reranked list can be shorter than what Algolia returned. That's usually what you want on a results page. If you'd rather keep every candidate, append the ones Latimal left out after the ranked block.
A single /search call takes up to 512 corpus items, so 50 to 200 candidates fits comfortably. Each rerank is one API call.
When Algolia finds nothing
Descriptive queries like "something warm for a rainy day" often return zero keyword hits. When that happens inside a single restaurant, search its menu directly with Latimal:
def search_restaurant(query, restaurant_menu, top_k=10):
hits = search_menu(query, restaurant_id=restaurant_menu[0]["restaurant_id"])
if hits:
return hits
names = [item["name"] for item in restaurant_menu][:512]
return latimal.search(query, corpus=names, top_k=top_k)["results"]2. Add cuisine facets with /classify
Classify every item once at index time and store the label as a record attribute. Algolia then handles faceting and filtering as usual.
def classify_records(records):
names = [record["name"] for record in records]
labels = []
for batch in chunked(names, 512): # /classify: up to 512 items per call
labels.extend(latimal.classify(batch))
for record, label in zip(records, labels):
record["text_hash"] = text_hash(record["name"])
if label["cuisine"] != "uncertain":
record["cuisine"] = label["cuisine"]
record["cuisine_confidence"] = label["confidence"]
return records
algolia.set_settings(
index_name=INDEX,
index_settings={
"searchableAttributes": ["name"],
"attributesForFaceting": ["searchable(cuisine)", "filterOnly(restaurant_id)", "currency"],
},
)
algolia.save_objects(index_name=INDEX, objects=classify_records(menu), wait_for_tasks=True)Now a filter like cuisine:Thai or a cuisine refinement list in InstantSearch works across every restaurant, even when a restaurant never tagged its own dishes. Beverages, bakery items and desserts get their own labels, so the same facet also separates drinks and sweets from mains.
Items below Latimal's confidence threshold come back as "uncertain". The code above leaves the attribute off those records so they don't show up under a misleading facet value.
3. Add cross-language dish synonyms with /match
Algolia synonyms work best when someone has curated them. Latimal can do the curating: find dishes in your catalog that are the same thing under different names, confirm each pair with /match, and save the confirmed pairs as synonyms. If /match confirms that "Oyakodon" and "Chicken and Egg Rice Bowl" are the same dish, a search for either one surfaces both restaurants.
First, find candidate pairs. Latimal vectors are L2-normalized, so a dot product gives cosine similarity:
import numpy as np
def candidate_pairs(names, per_item=3, floor=0.80):
vectors = []
for batch in chunked(names, 5000): # /embed/batch: up to 5,000 items per call
vectors.extend(latimal.embed_batch(batch))
matrix = np.array(vectors)
sims = matrix @ matrix.T
pairs = set()
for i in range(len(names)):
for j in np.argsort(-sims[i])[1:per_item + 1]:
if sims[i, j] >= floor and names[i].lower() != names[j].lower():
pairs.add(tuple(sorted((names[i], names[j]))))
return list(pairs)The full similarity matrix is fine for a few thousand distinct names. For a bigger catalog, run the same idea per cuisine or use an approximate nearest-neighbor library.
Then confirm the candidates. /match takes up to 100 pairs per call and flags dietary and protein conflicts, so you can keep pairs like "Chicken Tacos" and "Mushroom Tacos" out of your synonym list:
def confirmed_synonyms(pairs):
confirmed = []
for batch in chunked(pairs, 100): # /match: up to 100 pairs per call
for result in latimal.match(pairs=batch)["results"]:
if result["match"] and not result["dietary_conflict"] and not result["protein_conflict"]:
confirmed.append((result["text_a"], result["text_b"]))
return confirmed
names = sorted({record["name"] for record in menu})
synonyms = [
{
"objectID": "latimal-" + text_hash(a + "|" + b)[:16],
"type": "synonym",
"synonyms": [a.lower(), b.lower()],
}
for a, b in confirmed_synonyms(candidate_pairs(names))
]
if synonyms:
algolia.save_synonyms(index_name=INDEX, synonym_hit=synonyms, forward_to_replicas=True)The latimal- prefix on each synonym's objectID keeps generated synonyms separate from the ones your team writes by hand, and the hash makes reruns idempotent. Review the first batch before you save it, the same way you'd review any synonym list. Your Algolia plan sets how many synonyms an index can hold, so start with your highest-traffic dishes.
4. Keep records fresh when menus change
Only a name change needs Latimal. Compare the stored text_hash with the current name and reclassify just the items that differ.
def sync_records(current_records, stored_hashes):
"""stored_hashes maps objectID to the text_hash you last sent to Algolia."""
renamed = [r for r in current_records if stored_hashes.get(r["objectID"]) != text_hash(r["name"])]
unchanged = [r for r in current_records if stored_hashes.get(r["objectID"]) == text_hash(r["name"])]
if renamed:
# save_objects replaces the whole record, so stale cuisine labels go away too
algolia.save_objects(index_name=INDEX, objects=classify_records(renamed))
if unchanged:
algolia.partial_update_objects(
index_name=INDEX,
objects=[{"objectID": r["objectID"], "price": r["price"], "currency": r["currency"]} for r in unchanged],
)
current_ids = {r["objectID"] for r in current_records}
removed = [object_id for object_id in stored_hashes if object_id not in current_ids]
if removed:
algolia.delete_objects(index_name=INDEX, object_ids=removed)Rebuild synonyms nightly or weekly. New dish names pick up synonyms on the next run, and the rerank step covers them in the meantime.
Related
- POST /search for reranking and per-restaurant search
- POST /classify for cuisine labels
- POST /match for confirming dish pairs
- POST /embed/batch for candidate generation
- Search integration guide
- Benchmarks
- Aggregator search use case
- All integrations