Skip to content

Integration

Semantic menu search with Postgres pgvector and Supabase

If your menus already live in Postgres, you may not need a separate search engine at all. With the pgvector extension you can keep Latimal vectors in the same table as the dish, filter with plain WHERE clauses, and combine vector and full-text ranking in one SQL query. Everything here works on self-hosted Postgres and on Supabase, which ships pgvector.

Prerequisites

  • A Latimal API key in LATIMAL_API_KEY. See Authentication.
  • Postgres with the pgvector extension (0.8 or later recommended for filtered queries), or a Supabase project.
  • A connection string in DATABASE_URL. On Supabase, copy it from the project's database connection settings.
  • Python 3.9+ with requests, psycopg 3 and the pgvector adapter.
Shell
pip install requests "psycopg[binary]" pgvector numpy

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": "paris-19-0007", "restaurant_id": "paris-19", "name": "Croque Monsieur", "price": 11.00, "currency": "EUR"},
    {"id": "lima-03-0002", "restaurant_id": "lima-03", "name": "Ceviche Clásico", "price": 11.50, "currency": "USD"},
    {"id": "beirut-07-0011", "restaurant_id": "beirut-07", "name": "Falafel Wrap w/ Tahini", "price": 6.50, "currency": "USD"},
    {"id": "osaka-22-0008", "restaurant_id": "osaka-22", "name": "Tonkotsu Ramen", "price": 8.00, "currency": "USD"},
    {"id": "london-41-0002", "restaurant_id": "london-41", "name": "Pad Kra Pao Gai", "price": 14.00, "currency": "EUR"},
    {"id": "austin-03-0012", "restaurant_id": "austin-03", "name": "**NEW** Chicken Tinga Tacos (3 pcs)", "price": 13.00, "currency": "USD"},
]

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

2. Create the table

pgvector columns have a fixed size, so the script creates the table from the dims value you read in step 1. The fts column is a generated full-text vector for the keyword half of hybrid search.

Python
import numpy as np
import psycopg
from pgvector.psycopg import register_vector

conn = psycopg.connect(os.environ["DATABASE_URL"], autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)


def ensure_table(dims):
    dims = int(dims)
    conn.execute(f"""
        CREATE TABLE IF NOT EXISTS menu_items (
            id                 text PRIMARY KEY,
            restaurant_id      text NOT NULL,
            name               text NOT NULL,
            price              numeric NOT NULL,
            currency           text NOT NULL,
            cuisine            text,
            cuisine_confidence real,
            text_hash          text NOT NULL,
            embedding          vector({dims}) NOT NULL,
            fts                tsvector GENERATED ALWAYS AS (to_tsvector('simple', name)) STORED
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS menu_items_embedding_idx ON menu_items USING hnsw (embedding vector_cosine_ops)")
    conn.execute("CREATE INDEX IF NOT EXISTS menu_items_fts_idx ON menu_items USING gin (fts)")
    conn.execute("CREATE INDEX IF NOT EXISTS menu_items_restaurant_idx ON menu_items (restaurant_id)")
    conn.execute("CREATE INDEX IF NOT EXISTS menu_items_cuisine_idx ON menu_items (cuisine)")


ensure_table(dims)

The simple text search configuration skips language-specific stemming, which keeps keyword matching predictable for a catalog that mixes English, Spanish, Japanese and everything else. Latimal's vectors handle the cross-language side.

On Supabase you can also enable the extension from the dashboard. If you'd rather keep it out of the public schema, run create extension if not exists vector with schema extensions; once in the SQL editor.

3. Upsert the items

Python
UPSERT = """
    INSERT INTO menu_items (id, restaurant_id, name, price, currency, cuisine, cuisine_confidence, text_hash, embedding)
    VALUES (%(id)s, %(restaurant_id)s, %(name)s, %(price)s, %(currency)s, %(cuisine)s, %(cuisine_confidence)s, %(text_hash)s, %(embedding)s)
    ON CONFLICT (id) DO UPDATE SET
        restaurant_id = EXCLUDED.restaurant_id,
        name = EXCLUDED.name,
        price = EXCLUDED.price,
        currency = EXCLUDED.currency,
        cuisine = EXCLUDED.cuisine,
        cuisine_confidence = EXCLUDED.cuisine_confidence,
        text_hash = EXCLUDED.text_hash,
        embedding = EXCLUDED.embedding
"""


def upsert(items):
    rows = [
        {**item, "cuisine": item.get("cuisine"), "cuisine_confidence": item.get("cuisine_confidence"),
         "embedding": np.array(item["embedding"])}
        for item in items
    ]
    with conn.cursor() as cur:
        cur.executemany(UPSERT, rows)


upsert(items)

Semantic search with filters and facets

<=> is pgvector's cosine distance operator, so 1 - distance gives cosine similarity. Ordering by the distance expression lets Postgres use the HNSW index.

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 search_menu(query, cuisine=None, restaurant_id=None, limit=10):
    vector = np.array(embed_query(query))
    rows = conn.execute(
        """
        SELECT id, name, price, currency, cuisine, 1 - (embedding <=> %(q)s) AS similarity
        FROM menu_items
        WHERE (%(cuisine)s::text IS NULL OR cuisine = %(cuisine)s)
          AND (%(restaurant_id)s::text IS NULL OR restaurant_id = %(restaurant_id)s)
        ORDER BY embedding <=> %(q)s
        LIMIT %(limit)s
        """,
        {"q": vector, "cuisine": cuisine, "restaurant_id": restaurant_id, "limit": limit},
    ).fetchall()
    return rows


def cuisine_facets(restaurant_id=None):
    return conn.execute(
        """
        SELECT cuisine, count(*) FROM menu_items
        WHERE cuisine IS NOT NULL AND (%(rid)s::text IS NULL OR restaurant_id = %(rid)s)
        GROUP BY cuisine ORDER BY count(*) DESC
        """,
        {"rid": restaurant_id},
    ).fetchall()


for row in search_menu("something fresh and citrusy"):
    print(row)

With selective filters, an approximate index can return fewer rows than LIMIT because it filters after the scan. pgvector 0.8 added iterative index scans for this. Turn them on per session with SET hnsw.iterative_scan = relaxed_order;.

Hybrid search with reciprocal rank fusion

This query ranks items by vector distance and by full-text rank separately, then merges the two lists with reciprocal rank fusion. Exact dish names score on both sides, while descriptive or misspelled queries come through on the vector side alone.

Python
HYBRID = """
WITH semantic AS (
    SELECT id, row_number() OVER (ORDER BY dist) AS rank
    FROM (
        SELECT id, embedding <=> %(q)s AS dist
        FROM menu_items
        ORDER BY embedding <=> %(q)s
        LIMIT 50
    ) nearest
),
keyword AS (
    SELECT id, row_number() OVER (ORDER BY score DESC) AS rank
    FROM (
        SELECT id, ts_rank_cd(fts, websearch_to_tsquery('simple', %(text)s)) AS score
        FROM menu_items
        WHERE fts @@ websearch_to_tsquery('simple', %(text)s)
        ORDER BY score DESC
        LIMIT 50
    ) matched
)
SELECT m.id, m.name, m.price, m.currency, m.cuisine,
       coalesce(1.0 / (60 + s.rank), 0) + coalesce(1.0 / (60 + k.rank), 0) AS rrf_score
FROM semantic s
FULL OUTER JOIN keyword k USING (id)
JOIN menu_items m USING (id)
ORDER BY rrf_score DESC
LIMIT %(limit)s
"""


def hybrid_search(query, limit=10):
    return conn.execute(HYBRID, {"q": np.array(embed_query(query)), "text": query, "limit": limit}).fetchall()

The constant 60 is the usual RRF smoothing value. To weight one side more, multiply its term.

Calling it from Supabase clients

If your app talks to Supabase through its client libraries, wrap the semantic query in a SQL function and call it over RPC. Run this once in the Supabase SQL editor:

Text
create or replace function match_menu_items(
  query_embedding vector,
  match_count int default 10,
  cuisine_filter text default null
)
returns table (id text, name text, price numeric, currency text, cuisine text, similarity float)
language sql stable
as $$
  select id, name, price, currency, cuisine, 1 - (embedding <=> query_embedding) as similarity
  from menu_items
  where cuisine_filter is null or cuisine = cuisine_filter
  order by embedding <=> query_embedding
  limit match_count;
$$;

Then call it from Python (or any Supabase client), passing the Latimal query vector:

Python
from supabase import create_client

supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])

matches = supabase.rpc(
    "match_menu_items",
    {"query_embedding": list(embed_query("spicy noodles")), "match_count": 10, "cuisine_filter": "Thai"},
).execute()
print(matches.data)

Keep the Latimal API key on your server or in a Supabase Edge Function. Never ship it to a browser or mobile app.

5. Keep the table fresh when menus change

Only a name change needs Latimal. Compare the stored text_hash, re-enrich renamed or new items, patch prices in place, and delete what's gone.

Python
def sync_restaurant(restaurant_id, current_items):
    """Bring one restaurant's rows in line with its current menu."""
    existing = dict(conn.execute(
        "SELECT id, text_hash FROM menu_items WHERE restaurant_id = %s", (restaurant_id,)
    ).fetchall())

    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"])]
    current_ids = [item["id"] for item in current_items]

    with conn.transaction():
        if to_enrich:
            upsert(enrich(to_enrich))
        with conn.cursor() as cur:
            cur.executemany(
                "UPDATE menu_items SET price = %(price)s, currency = %(currency)s WHERE id = %(id)s",
                to_patch,
            )
        conn.execute(
            "DELETE FROM menu_items WHERE restaurant_id = %s AND NOT (id = ANY(%s))",
            (restaurant_id, current_ids),
        )

Run it from a POS webhook, a feed import, or a nightly job. Because the HNSW index updates on every insert, there's no separate re-index step.