Integration
Semantic menu search with Pinecone
On this page
Pinecone handles the vector storage and scaling so you can focus on relevance. This recipe stores a Latimal vector and a cuisine label on every dish in a Pinecone index, searches with metadata filters, and optionally reranks the top results with /search.
The code uses Pinecone's document index API from Python SDK v10. If you're on an older SDK with an existing vector index, the same flow maps onto index.upsert and index.query. Check Pinecone's docs for the version you run.
Prerequisites
- A Latimal API key in
LATIMAL_API_KEY. See Authentication. - A Pinecone project and API key in
PINECONE_API_KEY. - Python 3.9+ with requests and the Pinecone SDK.
pip install requests "pinecone>=10"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.
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": "melbourne-04-0016", "restaurant_id": "melbourne-04", "name": "Smashed Avo on Sourdough", "price": 13.00, "currency": "USD"},
{"id": "tokyo-11-0003", "restaurant_id": "tokyo-11", "name": "Oyakodon", "price": 5.00, "currency": "USD"},
{"id": "madrid-07-0012", "restaurant_id": "madrid-07", "name": "Tortilla Española", "price": 7.00, "currency": "EUR"},
{"id": "chicago-15-0001", "restaurant_id": "chicago-15", "name": "Deep Dish Pepperoni Pizza", "price": 24.00, "currency": "USD"},
{"id": "marrakech-03-0009", "restaurant_id": "marrakech-03", "name": "Lamb Tagine with Prunes", "price": 12.00, "currency": "USD"},
{"id": "seoul-06-0014", "restaurant_id": "seoul-06", "name": "Dolsot Bibimbap", "price": 9.50, "currency": "USD"},
]
items = enrich(menu)
dims = len(items[0]["embedding"]) # read the vector size from the response, never hardcode it2. Create the index
The dense vector field's size comes from the dims value you read in step 1. Fields you don't declare in the schema, like cuisine and restaurant_id, are stored as metadata at upsert time and can be used in filters.
import time
from pinecone import Pinecone, SchemaBuilder
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
INDEX_NAME = "menu-items"
NAMESPACE = "menus"
def ensure_index(dims):
if not pc.indexes.exists(name=INDEX_NAME):
schema = (
SchemaBuilder()
.add_dense_vector_field("embedding", dimension=dims, metric="cosine")
.build()
)
pc.indexes.create(name=INDEX_NAME, schema=schema)
while not pc.indexes.describe(name=INDEX_NAME).status.ready:
time.sleep(2)
return pc.index(name=INDEX_NAME)
index = ensure_index(dims)Pinecone's schemas can't be changed after creation. If you ever switch to a different dimension on the Latimal side, create a new index and re-embed into it.
3. Upsert the items
Pinecone document IDs go in _id. Metadata values must be flat (strings, numbers, booleans or lists of strings), which fits menu fields well.
def to_document(item):
doc = {key: value for key, value in item.items() if key != "id"}
doc["_id"] = item["id"]
return doc
for batch in chunked(items, 500):
index.documents.upsert(namespace=NAMESPACE, documents=[to_document(item) for item in batch])Requests are capped at 1,000 documents and 2 MB, so 500 per batch leaves room for longer names. Documents are indexed asynchronously, so a fresh upsert can take a few seconds to show up in search.
4. Search with metadata filters
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])
FIELDS = ["name", "restaurant_id", "price", "currency", "cuisine"]
def search_menu(query, cuisine=None, restaurant_ids=None, top_k=10):
conditions = []
if cuisine:
conditions.append({"cuisine": {"$eq": cuisine}})
if restaurant_ids:
conditions.append({"restaurant_id": {"$in": list(restaurant_ids)}})
params = {
"namespace": NAMESPACE,
"top_k": top_k,
"score_by": [{"type": "dense_vector", "fields": ["embedding"], "values": list(embed_query(query))}],
"include_fields": FIELDS,
}
if conditions:
params["filter"] = conditions[0] if len(conditions) == 1 else {"$and": conditions}
results = index.documents.search(**params)
return [{"id": m.id, "score": m.score, **{f: getattr(m, f, None) for f in FIELDS}} for m in results.matches]
for hit in search_menu("hearty slow-cooked stew"):
print(f"{hit['name']} ({hit['price']} {hit['currency']}) score={hit['score']:.3f}")Pinecone doesn't return facet counts, so count cuisines over the returned matches, or over a larger top_k if you want a fuller sidebar:
from collections import Counter
hits = search_menu("brunch", top_k=100)
facets = Counter(hit["cuisine"] for hit in hits if hit["cuisine"])5. Optional: rerank the top results with /search
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.
def search_and_rerank(query, candidates=50, top_k=10, **filters):
hits = search_menu(query, top_k=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"]]]6. Keep the index fresh when menus change
Pinecone overwrites the whole document on upsert, so every changed item gets a full document with its vector. Keep the last text_hash you synced for each item in your own database, and only call Latimal for items whose name changed.
def sync_restaurant(current_items, synced):
"""synced maps item ID to the full item dict (with embedding) you last upserted."""
changed, renamed = [], []
for item in current_items:
previous = synced.get(item["id"])
if previous is None or previous["text_hash"] != text_hash(item["name"]):
renamed.append(item) # new or renamed: re-embed and re-classify
elif previous["price"] != item["price"] or previous["currency"] != item["currency"]:
changed.append({**previous, **item}) # price change: reuse the stored vector and labels
docs = [to_document(item) for item in enrich(renamed)] if renamed else []
docs += [to_document(item) for item in changed]
for batch in chunked(docs, 500):
index.documents.upsert(namespace=NAMESPACE, documents=batch)
current_ids = {item["id"] for item in current_items}
removed = [item_id for item_id in synced if item_id not in current_ids]
for batch in chunked(removed, 1000):
index.documents.delete(namespace=NAMESPACE, ids=batch)If you'd rather not store vectors in your database, re-embed changed items too. A batch of up to 5,000 names is a single Latimal API call, so a busy day of price edits still costs very little.
Related
- POST /embed and POST /embed/batch for vectors
- POST /classify for cuisine labels
- POST /search for reranking
- Search integration guide
- Benchmarks
- Aggregator search use case
- All integrations