Design and Implementation of a Local Recommendation System for Multi-Cuisine Restaurants
This article explains how to design and implement a local recommendation system for discovering multi-cuisine restaurants. It covers the core engineering challenges, a five-layer system architecture, POI and cuisine data modeling, multi-source data fusion, menu-text structuring with dictionary-based matching and large language model assistance, quality scoring, multi-stage retrieval and ranking, reranking for diversity and constraints, online serving, evaluation, compliance and governance, and a phased implementation roadmap. Readers will gain a practical blueprint for building restaurant recommendation services that handle inconsistent data sources, fast-changing content, and personalized user preferences.
1. Problem Definition: Engineering Challenges Behind a Recommendation Problem
In cities with a diverse range of international cuisines, users often ask a similar question: Which multi-cuisine restaurants in this city are worth recommending?
The question appears simple, but it hides several technical challenges:
- Multiple and inconsistent information sources: reviews, recommendation posts, map data, restaurant-published menus, and user-generated text overlap and may contradict one another.
- Multiple decision dimensions: cuisine and country of origin, signature dishes, flavor profiles, price, distance, wait time, and dining scenarios all influence user decisions.
- Rapidly changing data: menu updates, limited-time openings, and rating fluctuations can quickly make recommendation results stale.
- User preferences vary widely: for the same city, different users may have completely opposite preferences for spiciness, taste, and dining scenarios.
Manually maintained lists cannot support continuous iteration. From an engineering perspective, the problem should be abstracted into a composite system consisting of POI knowledge construction + multimodal content understanding + hybrid retrieval + ranking and recommendation.
2. Overall Architecture
The system can be divided into five layers:
- Data ingestion layer: collects structured metadata and textual reviews, then stores deduplicated and normalized data into a data lake.
- Knowledge construction layer: recognizes dishes and cuisines, computes word-of-mouth labels, and builds vector representations.
- Storage and indexing layer: relational metadata, inverted indexes, and vector indexes work together.
- Retrieval and ranking layer: candidates are filtered progressively through recall, coarse ranking, fine ranking, and reranking.
- Service and operations layer: provides unified query interfaces, A/B experiments, monitoring, and alerting.
Ingestion → Cleaning & deduplication → Dish/cuisine recognition → Word-of-mouth & vector construction → Indexes↓Query → Recall → Fine ranking → Reranking → Results
3. Data Model: Turning Restaurants into Computable Structures
1. Core Entities
- Restaurant POI: name, coordinates, address, business status, opening hours, and average price range.
- Cuisine and country of origin: hierarchical classifications, for example South American > Peruvian / Argentine. Country of origin is not equivalent to cuisine, and one restaurant may serve multiple culinary styles.
- Dishes: standard names, aliases such as Chinese names or foreign-language names, cuisine category, and flavor tags such as sour-spicy or grilled.
- Reviews: text, rating, publication time, and upload channel.
- User preferences: explicitly selected taste tags and profiles inferred from historical behavior.
2. Example Fields
{"poi_id": "p_10086","name": "Sample Restaurant A","location": { "lng": 121.4456, "lat": 31.2193, "grid": "6x3" },"cuisines": ["peruvian", "argentine"],"dishes": [{ "name": "ceviche", "cuisine": "peruvian", "tags": ["sour", "seafood"] },{ "name": "lomo saltado", "cuisine": "peruvian", "tags": ["stir-fried", "beef"] }],"price_band": 2,"score": { "overall": 4.4, "taste": 4.5, "env": 4.1, "freshness": 0.82 }}
3. Modeling Principles
- Separate cuisine from country of origin: avoid confusing “the restaurant comes from a country” with “the dish belongs to a cuisine”.
- Use multi-valued tags: store tags as arrays rather than enum fields, making it easier to recall and diversify by flavor.
- Separate raw data from derived data: raw reviews should remain immutable for traceability; word-of-mouth labels and vectors can be recomputed periodically by offline jobs.
4. Data Ingestion and Knowledge Construction
1. Multi-Source Fusion and Entity Normalization
The same restaurant may appear with different names across channels, such as mixed Chinese-English names, missing or extra spaces, or abbreviations.
Candidate matching can be performed using city + grid + name similarity: first narrow the candidate set by grid, then compute name similarity using edit distance, and finally validate consistency using address similarity.
import refrom difflib import SequenceMatcherdef norm_name(s: str) -> str:return re.sub(r"[\s\W_]+", "", s.lower()) # Remove whitespace and punctuation; normalize casedef is_same_poi(a: dict, b: dict, th: float = 0.85, max_dist: float = 150.0) -> bool:if a["city"] != b["city"] or a["grid"] != b["grid"]:return False # Grid prefiltering to reduce comparison costif a["dist_to"](b) > max_dist: # Distance check to avoid merging same-name POIs incorrectlyreturn Falsesim = SequenceMatcher(None, norm_name(a["name"]), norm_name(b["name"])).ratio()return sim >= th
2. Structuring Menu Text
In menus and reviews, dish names may appear as translated names, original foreign-language names, or nicknames. A two-stage approach is recommended: alias dictionary + large language model extraction.
- Stage 1: use an alias dictionary for fast matching. It covers high-frequency dishes and fixed translations, with low cost and low latency.
- Stage 2: for text that fails to match or remains ambiguous, use a large language model inference service to extract dishes, flavors, and dining scenarios, and require structured output for direct downstream use.
- Key principle: narrow candidates before calling the model. Menu text can be noisy and long, so advertisements and irrelevant passages should be filtered first.
import json, reDISH_ALIASES = {"ceviche": ["cebiche", "seviche"],"lomo saltado": ["peruvian beef stir-fry", "lomo saltado"],"empanada": ["stuffed pastry", "empanada"],"churros": ["fried dough pastry", "churros"],}def extract_dishes(text: str) -> list[str]:hits = set()for std, aliases in DISH_ALIASES.items():if any(a.lower() in text.lower() for a in [std] + aliases):hits.add(std)return sorted(hits)# Example: structured output. In production, schema validation should be added# for field types, enum ranges, and confidence scores.SCHEMA_PROMPT = """Extract dishes from menu text and output only a JSON array. Each element should look like:{"name": "standard dish name", "cuisine": "cuisine", "tags": ["flavor or cooking style"], "confidence": 0.0-1.0}Requirements: preserve the original meaning, do not fabricate information, and keep confidence below 0.5 when uncertain."""def parse_model_output(raw: str) -> list[dict]:data = json.loads(raw) # In practice, schema validation is requiredreturn [d for d in data if d["confidence"] >= 0.5]
3. Multilingual Mapping for Cuisines and Countries
Cuisine names vary greatly across languages and countries. A standardized vocabulary is needed. Each cuisine node should include:
- a standard ID;
- aliases in multiple languages and the corresponding parent node;
- representative dishes and flavor tags.
During mapping, match aliases from longest to shortest to avoid false matches caused by short aliases. The vocabulary should be version-controlled. New terms should first enter a review queue and then be merged into the official version.
4. Word-of-Mouth Analysis and Quality Scoring
The word-of-mouth score consists of three parts:
- Dimension-level sentiment: analyze sentiment across dimensions such as taste, environment, service, and value for money.
- Freshness decay: assign higher weights to recent reviews.
- Credibility correction: remove suspicious reviews and apply weights based on channel credibility.
Freshness decay can be expressed as follows:
import mathdef freshness(days: float, half_life: float = 180.0) -> float:return 0.5 ** (max(days, 0.0) / half_life) # Half-life of 180 days
5. Retrieval and Ranking
1. Multi-Stage Recall
- Keyword recall: relevance scoring based on inverted indexes. Literal matching is reliable and explainable.
- Vector recall: semantic vector retrieval handles synonyms and cross-language expressions, such as matching “spicy seafood cold dish” with ceviche.
- Structured recall: filter by grid radius, business status, price range, and cuisine constraints.
During query understanding, a lightweight model can first parse a natural-language question into structured conditions:
{ "city": "Sample City", "cuisines": ["peruvian", "argentine"], "dist_max": 3000 }
2. Fusion and Fine Ranking
Candidates from different recall channels can be merged using reciprocal rank fusion, or RRF. Compared with directly adding scores from different scales, RRF relies only on ranks and is more robust.
def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:scores: dict[str, float] = {}for results in rankings:for rank, doc_id in enumerate(results):scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1)return sorted(scores.items(), key=lambda x: x[1], reverse=True)
Fine ranking can use multi-factor linear scoring. Weights are calibrated through offline experiments and online A/B testing.
import mathWEIGHTS = {"dist": 0.15, "quality": 0.30, "match": 0.25, "cuisine": 0.20, "fresh": 0.10}def score(dist_km: float, quality: float, match: float,cuisine_fit: float, days: float) -> float:return (WEIGHTS["dist"] * math.exp(-dist_km / 3.0) # Distance decay: slow within 3 km, then drops faster+ WEIGHTS["quality"] * quality # Quality score normalized to [0, 1]+ WEIGHTS["match"] * match # Matching score from the recall stage+ WEIGHTS["cuisine"] * cuisine_fit # Fit between cuisine and query intent+ WEIGHTS["fresh"] * (0.5 ** (max(days, 0) / 180)))
3. Reranking: Diversity and Constraints
Fine-ranked results still need two additional steps: avoid concentrating results on the same cuisine or the same signature dish, and ensure hard constraints such as flavor and dining scenario are not violated.
def rerank(items: list[dict], k: int = 10,per_cuisine: int = 3, alpha: float = 0.7) -> list[dict]:picked: list[dict] = []counts: dict[str, int] = {}pool = [i for i in items if not i.get("closed")] # Hard constraint: filter out closed POIswhile pool and len(picked) < k:best, best_val = None, -float("inf")for it in pool:if counts.get(it["cuisine"], 0) >= per_cuisine:continuepenalty = max([it.get("sim", lambda _: 0.0)(p) for p in picked], default=0.0)val = alpha * it["score"] - (1 - alpha) * penalty # MMR-style: balance relevance and diversityif val > best_val:best, best_val = it, valpicked.append(best)counts[best["cuisine"]] = counts.get(best["cuisine"], 0) + 1pool.remove(best)if len(picked) < k: # Relax cuisine limits when the quota is exhaustedrest = [i for i in pool if i not in picked]picked.extend(sorted(rest, key=lambda x: x["score"], reverse=True)[: k - len(picked)])return picked
4. Cold Start and Exploration
- User cold start: initially build user preferences from explicitly selected taste tags. When information is insufficient, use city-level popularity and a diversity-first default strategy.
- Restaurant cold start: newly listed restaurants lack reviews. They can receive short-term traffic support, and initial scores can be estimated from similar restaurants associated by cuisine and dishes.
- Exploration mechanism: randomly diversify candidates with a small probability. This helps collect new feedback and prevents long-tail restaurants from being permanently buried.
6. Online Service and Cloud Deployment
The query interface accepts both structured conditions and a natural-language question. It returns ranked results with dish names, quality signals, and recommendation reasons. Recommendation reasons are generated from templates: fields come from traceable structured data, avoiding distortion caused by free-form generation.
{"total": 47,"items": [{"poi_id": "p_10086","name": "Sample Restaurant A","cuisines": ["peruvian"],"distance_m": 620,"price_band": 2,"score": 0.83,"highlights": ["ceviche", "lomo saltado"],"reasons": ["Signature seafood cold dish matches your taste preference","Stable word-of-mouth over the past six months"]}]}
For cloud deployment, the following general categories can be referenced:
- Object storage: stores raw menu and review files, offline compute outputs, and exported index snapshots.
- Message queues: smooth peak loads for ingestion, parsing, vector construction, and other tasks, while supporting failure retries.
- Container platforms: host retrieval and ranking services, with elastic scaling for dinner-peak traffic.
- Relational databases: store POI metadata and cuisine vocabularies.
- Logging services: record query chains, impressions, and clicks for offline evaluation.
- Monitoring and alerting: track interface P99 latency, empty-result rate, recall coverage, and data-job latency.
The above are general solution categories, not an endorsement of any specific cloud vendor. If Baidu AI Cloud is used, general product categories such as object storage, message queues, container platforms, logging services, and monitoring/alerting can be adopted.
7. Evaluation System
1. Offline Metrics
- Relevance: calculate Recall@K and NDCG@K on a labeled evaluation set.
- Diversity: compute the entropy of cuisine distribution and the average intra-list similarity of results.
- Consistency: record inter-annotator agreement to ensure labeling quality.
- Stability: replay queries using different time snapshots and observe result stability.
2. Online Metrics
Click-through rate, save rate, detail-page dwell time, conversion rate, average number of restaurants viewed per user, and next-day retention.
3. Experimental Methods
- Traffic bucketing: hash user IDs into buckets so that the same user always enters the same experiment group.
- Metric evaluation: use two-sample tests to assess significance, set a minimum experiment duration, and avoid weekend and holiday fluctuations.
- Cross-validation: when offline performance and online metrics disagree, prioritize checking data leakage and feature leakage.
8. Compliance, Risk, and Engineering Governance
- Lawful data sources: follow service terms and the robots protocol, prefer licensed data, and respect content copyright.
- Personal information protection: follow data minimization principles, de-identify sensitive information such as phone numbers and precise addresses, and provide an opt-out entry for user profiles.
- Content authenticity: establish review moderation, abnormal rating detection, and merchant content labeling to avoid fake word-of-mouth affecting rankings.
- Content freshness: set expiration periods for menu and price fields. Expired content should automatically be downgraded to “subject to the store”.
- Service explainability: attach supporting reasons to recommendation results to reduce user concerns about “black-box recommendations”.
9. Implementation Roadmap and Recommendations
- Phase 1 — MVP: ingest only POI metadata and a small set of seed cuisines. Use keyword retrieval plus rule-based ranking to validate demand quickly.
- Phase 2: launch alias dictionaries and menu structuring. Introduce vector recall and quality scoring.
- Phase 3: introduce large language model extraction and semantic query understanding. Build A/B testing and monitoring systems.
- Phase 4: add personalized preferences and exploration strategies. Continuously optimize diversity and long-tail coverage.
A question such as “Which multi-cuisine restaurants in this city are worth recommending?” may appear to be a simple lifestyle question. Once decomposed, it is a typical recommendation-system engineering problem. Answer quality depends on four areas: whether data coverage is complete, whether knowledge extraction is accurate, whether retrieval and ranking balance relevance and diversity, and whether the evaluation system is scientific. Strengthening these four chains allows the recommendation service to continuously produce trustworthy results in a real, fast-changing data environment.
