DEV Community

YatesHolloway6872
YatesHolloway6872

Posted on

2026 Node.js Retrieval for Restaurant Menu Assistants: 5 Metadata Filters

Short answer: put hard menu facts in metadata first, then run semantic retrieval inside that slice. For a restaurant menu assistant, five filters—restaurant, location, service date, dietary flags, and availability—usually buy more answer quality than a larger embedding model. The trade is latency: every filter you can resolve before vector search shrinks the candidate set, but an over-strict filter can turn a useful answer into “nothing found.”

I run a one-person SaaS, so I measure infrastructure in revenue per hour. A menu assistant that answers in 250 ms but invents an allergen is not fast; it is expensive support work. The design below favors a small, inspectable pipeline that can ship weekly and lets me outsource the undifferentiated storage plumbing.

The decision note: filter first, rerank second

Retrieval path Best fit Latency shape Main risk
Metadata filter, then vector search Known restaurant, date, and diet constraints Lowest candidate count Missing or stale fields create false negatives
Vector search, then metadata check Messy user intent and incomplete queries More predictable recall, slower tail Irrelevant chunks consume the top-k budget
Keyword plus metadata filter Exact dish names, codes, and prices Fast for literal matches Synonyms and spelling variants are missed
Hybrid retrieval with a reranker Large menus and ambiguous dish language Highest p95 unless capped More moving parts and tuning work

My default is the first row, with a controlled fallback to the second when a filter is not stated or produces zero candidates. Keep the fallback visible in logs. Silent broadening is how a “vegetarian near me” question ends up citing a chicken dish from another branch.

Metadata is a contract, not decoration. Every chunk should carry a stable restaurant ID, branch or location ID, menu version, effective date, service window, currency, dietary claims, allergen list, and availability state. Store the original section heading and source URL beside the text so the answer can show its evidence.

What should a restaurant menu assistant filter before retrieval?

Start with fields that change the answer, not fields that merely describe it. A city filter is useful when a chain has different prices by branch. A cuisine label is less useful if the user already named a dish. The five gates I use are:

  1. restaurant_id and location_id: prevent cross-branch leakage.
  2. service_date and service_window: separate lunch, dinner, and seasonal menus.
  3. dietary_flags: model positive claims such as vegetarian or halal separately from the absence of an allergen.
  4. allergens: treat “contains nuts” as a fact, not an inferred negative.
  5. availability: distinguish listed, sold-out, and discontinued items.

Price belongs in structured data too. Do not embed “$18” and expect a vector distance to enforce “under $20.” Parse money into minor units, store the currency, and apply the range after the hard identity filters. This avoids comparing 18 dollars with 18 euros as if they were the same value.

Keep it boring.

The uncomfortable bit is null handling. If a dish has no allergen declaration, allergens: [] is not honest; use allergens: null or an explicit unknown state. The assistant should say it cannot verify the claim instead of treating missing metadata as safe.

A small Node.js retrieval contract

The application layer should compile user intent into a typed filter object. The vector store can remain replaceable because the contract contains ordinary JSON and a query string. This example intentionally keeps one query path; production code can add a keyword leg without changing the answer schema.

type MenuFilter = {
  restaurantId: string;
  locationId?: string;
  serviceDate: string;
  serviceWindow?: "breakfast" | "lunch" | "dinner";
  dietaryFlags?: string[];
  excludeAllergens?: string[];
  availability: "available" | "all";
  maxPriceMinor?: number;
  currency?: string;
};

type MenuHit = {
  id: string;
  text: string;
  metadata: {
    restaurant_id: string;
    location_id: string;
    service_date: string;
    availability: "available" | "sold_out" | "discontinued";
    price_minor?: number;
    currency?: string;
    dietary_flags?: string[];
    allergens?: string[] | null;
    source_url: string;
  };
  score: number;
};

function toFilterExpression(filter: MenuFilter): Record<string, unknown> {
  const expression: Record<string, unknown> = {
    restaurant_id: filter.restaurantId,
    service_date: filter.serviceDate,
  };
  if (filter.locationId) expression.location_id = filter.locationId;
  if (filter.serviceWindow) expression.service_window = filter.serviceWindow;
  if (filter.dietaryFlags?.length) expression.dietary_flags_all = filter.dietaryFlags;
  if (filter.excludeAllergens?.length) expression.allergens_none = filter.excludeAllergens;
  if (filter.availability === "available") expression.availability = "available";
  if (filter.maxPriceMinor !== undefined) expression.price_lte = filter.maxPriceMinor;
  if (filter.currency) expression.currency = filter.currency;
  return expression;
}

export async function retrieveMenu(
  question: string,
  filter: MenuFilter,
  embed: (text: string) => Promise<number[]>,
  search: (input: { vector: number[]; filters: Record<string, unknown>; limit: number }) => Promise<MenuHit[]>,
): Promise<MenuHit[]> {
  const vector = await embed(question);
  const hits = await search({
    vector,
    filters: toFilterExpression(filter),
    limit: 12,
  });
  return hits.filter((hit) => {
    const priceOk = filter.maxPriceMinor === undefined
      || hit.metadata.price_minor === undefined
      || hit.metadata.price_minor <= filter.maxPriceMinor;
    const currencyOk = !filter.currency || hit.metadata.currency === filter.currency;
    return priceOk && currencyOk;
  });
}
Enter fullscreen mode Exit fullscreen mode

There are two deliberate defenses here. The store receives identity and safety filters before similarity ranking, and the application rechecks price and currency after retrieval. Different stores express array predicates differently, so keeping this translation in one adapter prevents query syntax from leaking into prompts or UI code. It also gives me a single place to count empty results and fallback decisions.

Do not use an empty result as permission to remove every filter. Broaden one dimension at a time: first service window, then date tolerance, and only then location if the user asked for a chain-wide answer. Return the reason with the result, such as broadened: ["service_window"], so a response template can qualify its claim.

How do quality and latency change as filters get stricter?

Measure both before selecting an index or reranker. For each labeled question, record recall@k, filtered recall, answer latency at p50 and p95, empty-result rate, and citation correctness. A filter that raises precision but doubles p95 may be fine for a sit-down ordering flow and poor for a kiosk.

Use a small test matrix rather than a single average. Include a current lunch menu, a previous seasonal menu, a sold-out item, an item with unknown allergens, a branch with the same dish name, and a price in a second currency. Ten hand-checked cases expose more metadata mistakes than a thousand randomly generated questions.

The common failure modes are boring:

  • A menu update changes text but not effective_date, so yesterday's answer wins.
  • A branch inherits the chain's restaurant_id but loses its location_id, mixing prices.
  • “Vegan” is stored as a single string and an exact-array filter misses vegan-friendly.
  • A sold-out chunk remains semantically similar and outranks an available alternative.
  • A null allergen field is rendered as “no allergens.”

I once treated an empty filtered search as a retrieval failure and widened everything in one retry. The code removed the service window, then the date, then the location in a single promise chain, so the final response looked complete even though it came from a different branch's dinner menu. That made the latency graph look healthy while the citations became indefensible; a fast answer with the wrong branch is a support ticket wearing a success badge. The fix was less clever: classify empty results, preserve the hard restaurant boundary, and ask a follow-up when the missing field changes safety. I also kept the original filter object in the trace, along with each dimension the fallback relaxed, because a bare “no hits” counter cannot tell an ingestion problem from a genuinely narrow request.

Where the runner-up is the better choice

A filter-first design is not universal. Use vector-first retrieval when users routinely omit restaurant or date and the product can safely ask a clarification question. Use keyword search when dish names, item codes, and exact prices dominate. Use a hybrid path when menus contain multilingual descriptions or long preparation notes that lexical matching alone cannot cover.

The storage choice also has real trade-offs. PostgreSQL with pgvector keeps menu rows, permissions, and embeddings together, which simplifies joins but puts index tuning on your team. Qdrant exposes explicit payload filtering and is a focused vector service, while Weaviate combines vector and hybrid features with a larger operational surface. Pinecone offers managed index operations, but metadata and source-version policy still belong in your application. These are engineering boundaries, not a leaderboard.

The catch is operational ownership. A hosted vector index is unsuitable when your data policy requires self-managed residency or SQL transactions across menu and order records. A self-hosted stack is a poor fit when one person cannot spare weekly time for backups, upgrades, and capacity tests. Stick with the simpler path until a measured failure says otherwise.

For a solo SaaS, the winning architecture is the one I can explain during an incident: ingest a versioned menu, validate metadata, filter the safe slice, retrieve a bounded top-k, and cite the source URL. Ship that loop weekly. Outsource the undifferentiated index maintenance only when its boundary is clear.

References

Top comments (0)