餐廳菜單檢索:Node.js 中先篩選元資料,再做語義重排
Restaurant Menu Retrieval: Choose Metadata Filters Before Semantic Reranking in Node.js
作者建議餐廳菜單檢索先按餐廳、分店、服務時段、語言及飲食限制篩選,再對合資格項目進行語義重排。若篩選後沒有結果,應避免擴大搜尋範圍;並核對來源與索引的版本及有效時間,防止過期或重複紀錄進入結果。文章亦建議保留項目來源與版本,並監察索引延遲及重複有效紀錄。
When a menu assistant returns a convincing answer for the wrong location, the embedding model is rarely the first thing to blame. The usual fault is that retrieval allowed an impossible candidate into the result set.
Short answer: apply strict metadata filters for restaurant, service date, language, and dietary status before semantic search; add semantic reranking only inside that smaller, fresh candidate set. This keeps stale or out-of-scope menu items from becoming plausible answers.
The incident lesson: relevance cannot repair a bad scope
I treat a menu record as an operational object, not a paragraph. It has a restaurant ID, branch, menu version, effective time, service channel, language, allergens, and an embedding of the descriptive text. The text helps find “spicy noodle soup.” The fields decide whether that dish can be shown to this diner now.
The failure mode is easy to reproduce. A customer asks, “What vegetarian lunch can I order at the airport location today?” A vector search finds a highly similar item from the downtown branch. The answer sounds helpful, and a generic relevance score may even put it first. The assistant has still made a production error.
Scope first.
This is why I separate the retrieval path into two gates. Gate one is deterministic scope: tenant, branch, channel, locale, and an effective-time interval. Gate two is semantic similarity over the surviving rows. If gate one returns zero rows, the assistant should say that the menu has no matching item and offer a narrower clarification. It should not silently widen the branch or date filter.
Freshness needs its own check. A menu update should carry a version or updated_at value, and the index should expose the same value. During an incident, compare the source-of-truth version with the indexed version before tuning a model. A better embedding cannot make yesterday's price current.
How should a restaurant menu assistant build retrieval with metadata filters?
Start with a canonical query object. Keep user language, normalized filters, and the retrieval timestamp separate so logs can explain every decision. In a Node.js service, this object can be passed to a database adapter, an OpenSearch-style adapter, or a self-hosted vector engine without changing the policy layer.
The adapter below is deliberately generic. It demonstrates the order of operations and the fail-closed behavior; the concrete vector query belongs in the adapter for the search system you operate.
package retrieval
import (
"context"
"time"
)
type MenuQuery struct {
RestaurantID string
BranchID string
Language string
Service string
QueryText string
AsOf time.Time
}
type MenuHit struct {
ID string
Restaurant string
Branch string
VersionTime time.Time
Score float64
}
type Searcher interface {
Search(ctx context.Context, q MenuQuery, limit int) ([]MenuHit, error)
}
func Retrieve(ctx context.Context, s Searcher, q MenuQuery) ([]MenuHit, error) {
if q.RestaurantID == "" || q.BranchID == "" || q.Language == "" || q.Service == "" {
return nil, nil // refuse an unscoped request
}
return s.Search(ctx, q, 20)
}
The comment is intentional: an empty result is safer than an unfiltered result for a transactional menu. In a real service, return a typed validation error and record which field was missing. Do not turn that error into a broad search as a convenience fallback.
Chunking affects the second gate. A chunk should preserve the smallest unit a diner can order or verify: item name, ingredients, allergen note, serving window, and the menu version. Splitting an allergen statement away from its item creates a retrieval hit that lacks the evidence needed for a safe answer. On the other hand, placing an entire 40-page menu in one chunk makes every item compete in the same vector representation.
I use parent-child linkage: retrieve item-level chunks, then hydrate the parent record for the final answer. Store the source offsets and version with each child. That makes a citation or support trace point to a real menu entry rather than to an arbitrary slice of text.
When should semantic search outrank strict filters?
Semantic search earns its place after the hard predicates. It is useful for spelling differences, multilingual dish names, and questions such as “something warm without dairy,” where exact token matching is weak. It is not a substitute for branch, date, or allergen policy.
The ranking stage should also be observable. Log the normalized filter set, candidate count before and after filtering, top score, index version, and answer latency. A sudden rise in zero-candidate queries may indicate a parser change; a rise in candidates from old versions points to an indexing lag. These signals are more actionable than a single aggregate relevance metric.
Set a review threshold instead of pretending every score is comparable. If the top two candidates are close and their dietary attributes disagree, ask a clarification question or show the source entries for confirmation. Your mileage may vary across languages and embedding models; calibrate thresholds with labeled menu questions, not with a synthetic benchmark alone.
Freshness, retries, and duplicate menu records
Near-duplicate records are common during imports. A branch may publish “Tomato soup” twice with different punctuation, or a crawler may write the same version twice after a retry. Deduplicate by a stable source ID and version first. Use semantic similarity as a review signal, not as permission to merge records automatically.
An idempotent ingestion key can be as simple as (restaurant_id, branch_id, source_item_id, menu_version). Upserts should preserve the newest effective record and mark older versions inactive. The retrieval filter then checks both active = true and the requested service interval.
I once started debugging a low-relevance alert by changing chunk size. I pulled a replay window from the ingest log, compared source IDs with active index IDs, and found the same item written twice after a retry. The records differed only in punctuation, so a semantic check made them look like legitimate near-duplicates rather than a clear data error. I then checked the menu-version timestamps and saw that both rows were eligible for the same service interval. The actual problem was a replayed import that left two active versions. The fix was a uniqueness constraint and a replay-safe consumer, followed by a backfill that marked the older row inactive and a replay of the affected questions. The lesson stuck: inspect cardinality and freshness before adjusting prompts or embeddings.
That is the whole point.
Keep the write path and read path explicit. A successful embedding call does not prove that the new vector is visible to the search index. Emit an event when the source version is accepted, another when the vector is indexed, and alert on the age difference between those events.
The trade-offs and the boundary of this advice
Strict filters add schema work. Every field used in a predicate needs normalization rules, migration coverage, and tests for missing values. They can also hide useful discovery queries: a diner asking “what is popular nearby?” may not know a branch ID. For that experience, use a separate discovery flow with a clearly broader policy and a different answer template.
Semantic reranking adds compute and another failure surface. It is not suitable when the source data has no trustworthy effective time or allergen metadata; fix the source contract first. It is also a poor fit for a tiny, static menu where a deterministic full-text query is easier to inspect.
The trade-off table I keep in a runbook looks like this:
| Choice | Good fit | Cost or risk |
|---|---|---|
| Hard metadata filters first | Branch-specific, time-sensitive ordering | Requires clean, indexed fields |
| Semantic reranking inside the set | Paraphrases and multilingual descriptions | Adds latency and threshold tuning |
| Deterministic text search only | Small, stable menus with exact names | Misses paraphrases and spelling variation |
| Broad discovery search | “Nearby” or exploratory questions | Must not be reused for order-eligibility answers |
Stick with deterministic search when the menu is small and policy-heavy. Add vectors when query language, not data volume, is the bottleneck. In either case, expose the selected record IDs and versions to operators so a support engineer can replay the decision.
A practical acceptance checklist
Before shipping, replay questions across branches, service windows, languages, and dietary constraints. Include an item that changes price or availability between two versions. Verify that an old version is excluded, a missing branch is rejected, and a duplicate source ID does not create two active hits.
Test the boundaries as contracts: filter parsing, time-zone conversion, index visibility, and answer citation. Measure p50 and p95 latency separately for filtering and reranking. Alert on empty-result rate, stale-index age, duplicate-active count, and unsupported-filter rate.
The RAG paper that introduced the retrieval-plus-generation framing is a useful conceptual reference, but the production guarantee comes from the data contract around retrieval. A fluent answer is the last step; scope and freshness decide whether it deserves to be shown.
References
來源:DEV Community · dev.to