Поиск недвижимости по текстовому запросу: метрики и признаки
Спроектируйте поиск недвижимости без явных фильтров: пользователь вводит свободный текст. Как на первом шаге определить метрики, признаки объявлений, query/user context и базовую схему retrieval/ranking?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Начать нужно с цели поиска и метрик: клики, открытия, сохранения, чаты/звонки, качественные лиды и revenue с guardrails по latency, пустым выдачам и релевантности. Для объявлений нужны geo, цена, комнаты, площадь, тип объекта, текстовые атрибуты и признаки из фото; дальше строится retrieval плюс ranker.
Подробный разбор
Сначала фиксируем продуктовую поверхность: поиск покупки, долгосрочной аренды, посуточной аренды, квартир или домов может иметь разные интенты. Метрики должны отражать не только CTR, но и открытия карточек, сохранения, сообщения, звонки, качественные лиды, сделки и revenue. Guardrails: latency, пустые выдачи, жалобы, географическое покрытие, paid/organic balance и seller-side liquidity.
Для item нужны структурные признаки: гео, цена, число комнат, площадь, этаж, тип объекта, тип сделки, доступность. Из текста можно извлекать мягкие атрибуты: ремонт, вид, парковка, техника, шум, близость к метро или парку. Из фото полезны качество, ракурс/комната, визуальные embeddings и признаки интерьера.
На первом шаге схема обычно двухэтапная: retrieval набирает кандидатов, ranker сортирует их более сложной моделью. Важно отдельно думать про query: если пользователь пишет свободный текст, часть запроса нужно превращать в структурные атрибуты, а часть поддерживать full-text и vector search.
Типичные ошибки
- Сразу перейти к embeddings без определения метрик и ограничений.
- Оставить только clicks и забыть про leads, звонки и revenue.
- Игнорировать geo, цену и тип объекта как жесткие ограничения.
Как сказать на собеседовании
- Начните с метрик и guardrails.
- Разделите item features, query understanding, retrieval и ranking.
Как превратить текстовый запрос в кандидатов для поиска недвижимости
Пользователь пишет свободный текстовый запрос по недвижимости, в котором могут быть частые атрибуты и редкие бытовые детали. Как превратить такой query в кандидатов через structured attributes, полнотекстовый поиск и векторный поиск?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Для частых и точных ограничений лучше извлекать атрибуты из query и искать по structured/full-text индексу. Для редких или мягких формулировок нужен vector search по описаниям/чанкам и, возможно, изображениям. Кандидатов из разных источников объединяем и передаем в ranker с признаками provenance.
Подробный разбор
Не стоит сводить все к одному embedding search. Для частых и важных ограничений - город, район, цена, комнаты, тип аренды, наличие техники, метро - полезен query parser, который превращает текст в атрибуты. Эти атрибуты можно матчить со структурными полями объявлений и full-text индексом.
Для long-tail формулировок, где нет заранее заведенного признака, нужен dense/vector retrieval. Описание объявления можно разбивать на чанки и строить embeddings, чтобы запросы вроде "тихая квартира рядом с парком" доставали релевантные объявления даже без точного флага. Lexical search все равно нужен для адресов, метро, редких имен и точных совпадений.
Candidate generation лучше делать гибридно: structured filters, BM25/full-text, vector index, freshness/popularity fallback и допустимые paid listings. В ranker нужно передавать provenance: откуда пришел кандидат и по каким признакам он совпал. Это помогает debug, объяснениям и контролю paid/organic баланса.
Типичные ошибки
- Заменить все фильтры одним opaque embedding search.
- Потерять точные geo/address/entity совпадения.
- Не передать в ranker признаки источника кандидата.
Как сказать на собеседовании
- Скажите: query parser плюс full-text плюс dense retrieval.
- Отдельно назовите long-tail атрибуты и candidate provenance.
ML System Design
How would you train the ranker for real-estate search, choose negatives, and blend paid monetized listings without destroying relevance?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Train on exposed query-listing pairs using graded actions, sampled and impression-based negatives, and position-bias correction. Blend monetization with relevance through expected value and hard relevance/quality guardrails.
Подробный разбор
The ranker row should represent a listing in a query and user context. Labels can be graded: impression with no action, open, favorite, message, call, qualified lead, booking or purchase. Exposure logs are important because unshown listings are not clean negatives.
Negatives can include random listings, shown-but-not-clicked impressions and hard negatives from the same city/price/type that were skipped in favor of clicked listings. Position bias must be handled with features, debiasing, counterfactual logging or cautious interpretation. Pairwise/listwise losses often fit ranking better than pure pointwise classification, but production simplicity matters.
Monetization should not be a raw score bonus. Better framing is expected marketplace value: relevance probability times business value, with constraints on relevance, geography, quality, paid quota, user harm and seller fairness. Keep organic and paid candidates eligible only when they satisfy the query; then blend with calibrated scores and A/B-test revenue, lead quality and user guardrails.
Типичные ошибки
- Treat every non-click as an equally strong negative.
- Add bid directly to relevance score without calibration.
- Optimize revenue while ignoring user and seller-side guardrails.
Как сказать на собеседовании
- Use graded labels and exposed impressions.
- Say “expected value with relevance guardrails” for paid listings.
Вопрос по метрикам
How would you evaluate the full search pipeline and its individual components offline and online?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Evaluate components with proxy labels and the whole pipeline with business A/B metrics. Always slice by geo, price, property type, query class, paid/organic mix and latency.
Подробный разбор
Component metrics answer whether each block works: attribute extraction F1, geo parsing accuracy, retrieval recall@K, ranker nDCG/MRR, calibration and coverage. These metrics are useful for debugging but do not prove product value.
The full pipeline needs online evaluation: CTR, listing opens, favorites, calls/messages, qualified leads, bookings/purchases, revenue and retention. Guardrails should include latency, empty results, complaint rate, diversity, long-tail coverage, fairness between paid and organic content and seller-side liquidity.
Slicing matters because real-estate search is heterogeneous. A model can improve Moscow rentals and hurt regional daily rentals, or improve cheap apartments and hurt premium new builds. Good evaluation reports slice by city/region, price band, property type, transaction type, query intent and paid-content exposure.
Типичные ошибки
- Use only offline nDCG and skip A/B testing.
- Average away important city and price-band regressions.
- Ignore latency and empty-result guardrails.
Как сказать на собеседовании
- Say “components offline, full pipeline online”.
- Name at least five important slices.
Вопрос про production ML
How would you handle geography in free-form real-estate queries and keep retrieval fast for millions of listings and high QPS?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Use geocoding/entity resolution for explicit places, user/session context for ambiguity, hierarchical geo cells for retrieval, and shard indexes by geo while precomputing listing embeddings offline.
Подробный разбор
Geo is not just another text token. Queries can mention city, district, metro, street, landmark or ambiguous names that exist in many regions. A robust system combines NER/geocoding, dictionaries, maps data, user/session location and selected transaction context.
Represent geo hierarchically: country, region, city, district, neighborhood, metro/landmark and a spatial cell such as geohash/H3. Retrieval can first choose eligible geo scopes, then query only relevant shards or partitions. If the query has no explicit geo, use product context and user defaults carefully.
For load, precompute listing embeddings and listing attribute indexes offline. Online work should mostly parse the query, fetch candidate lists from geo-sharded lexical/vector indexes, and run a bounded ranker. Use ANN parameters, cache hot query parses, batch neural query encoding when useful, and monitor p95/p99 latency by city and query type.
Типичные ошибки
- Let dense retrieval override hard geo constraints.
- Assume street names are globally unique.
- Compute item embeddings online for each query.
Как сказать на собеседовании
- Mention hierarchical geo resolution.
- Say item embeddings are precomputed offline.
Вопрос про production ML
Sketch the online architecture for query parsing, candidate generation, ranking and blending. How do services communicate and fail safely?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Keep the online path synchronous and bounded: query parser, retrieval services, feature fetch, ranker, blending and fallback. Use async queues for offline index/model updates, not for the user-facing critical path.
Подробный разбор
A simple online path is: API/search gateway receives query; query parser extracts text embedding, attributes and geo; retrieval services query lexical/vector/structured indexes; feature service fetches bounded item/user/context features; ranker scores candidates; blender applies paid/organic and business constraints; response is returned with logging.
Inter-service calls on the critical path are usually synchronous RPC/HTTP/gRPC with tight timeouts, retries where safe and circuit breakers. If the query parser or ranker fails, degrade to lexical/structured search, cached hot results, previous stable model or business-rule ranking. Kafka or another broker is better for offline index updates, feature refresh, training logs and model publish events, not for waiting on every user query.
Reliability needs health checks that execute real inference, p95/p99 latency monitoring, coverage metrics, cache hit rate, fallback rate, empty-result rate and rollback for model/index versions. Avoid passing huge embeddings or candidate payloads between too many services if co-locating retrieval and ranking is simpler and faster.
Типичные ошибки
- Put Kafka between every online service without a latency reason.
- Forget fallbacks when the query model or ranker is down.
- Pass large candidate payloads across many network hops.
Как сказать на собеседовании
- Separate online synchronous path from offline async updates.
- Name timeout, fallback, circuit breaker and rollback.
ML System Design
If the old product used filters rather than free-form text, how would you train a query parser or query encoder before real text-query logs exist?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Bootstrap from filter sessions by generating natural-language queries for filter combinations, add human/LLM validation, train the parser, then replace synthetic assumptions with real query logs after launch.
Подробный разбор
When historical text queries do not exist, the strongest source is existing filter behavior. A session with city, price, rooms, dates, amenities and clicked listings can be converted into one or several plausible text queries.
Use LLMs to generate diverse paraphrases from filter JSON, but keep the labels from the original structured filters. Add constraints so generated text does not invent attributes. Sample realistic partial filters, not only fully specified listings. Validate a subset with humans and build adversarial cases for ambiguous geo, slang, typos and long-tail amenities.
The first model can be a multi-label classifier/sequence tagger for attributes plus a geo resolver and text encoder. After launch, log real text queries, clicked/listed items and user corrections. Gradually reweight toward real data and keep synthetic data for coverage and regression tests.
Типичные ошибки
- Generate perfect synthetic queries that users would never type.
- Let the LLM invent labels not present in the source filters.
- Never replace synthetic labels with real user logs.
Как сказать на собеседовании
- Start from filter sessions.
- Mention human validation and post-launch real-query collection.
ML System Design
What improvements would you add after the baseline real-estate search works: user context, visual embeddings, VLMs, quality models or richer item representations?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Improve item representation with room/photo classification, image quality, extracted amenities and multimodal embeddings; add user/session context cautiously and measure gains by slices.
Подробный разбор
After a baseline works, richer item representations often pay off. For photos, classify room type, detect low-quality or irrelevant images, select the best cover photo, extract visible amenities and compute visual embeddings. For text, normalize attributes and enrich descriptions with extracted structured facts.
User and session context can improve relevance: previous searches, viewed listings, favorites, price tolerance, preferred districts, device, travel dates and transaction type. Use it carefully so the model does not override explicit query constraints.
VLMs can help with long-tail visual attributes such as "bright kitchen", "renovated bathroom" or "view of park", but they need evaluation for hallucinations and latency. Many VLM outputs are better used offline to enrich listings rather than online per query. Every improvement should be evaluated by query type, property type, geo and freshness because image-heavy gains may not generalize.
Типичные ошибки
- Use user personalization to override a clear query.
- Run expensive VLM inference online for every query-item pair.
- Ignore photo quality and room-type classification.
Как сказать на собеседовании
- Suggest offline VLM enrichment first.
- Separate explicit query intent from personalization.
VLM и чат-ассистент поверх поиска недвижимости
Как встроить VLM, поиск по картинкам и чат-ассистента в продукт поиска недвижимости так, чтобы они дополняли основной retrieval/ranking, а не заменяли его?
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
VLM лучше использовать в основном offline: извлекать признаки из фото, embeddings, room/view tags и обогащать объявления. Чат-ассистент должен работать поверх retrieval и проверенных фактов объявления, задавать уточнения и собирать подборки, но не выдумывать объекты и не обходить hard constraints ранжирования.
Подробный разбор
VLM полезна для понимания фотографий объявлений: тип комнаты, качество фото, вид из окна, наличие мебели или бытовых деталей, image embeddings и признаки, которых нет в структурных полях. Обычно это лучше делать offline-пайплайном обогащения объявлений, потому что online VLM-вызовы дорогие и могут галлюцинировать.
Поиск по картинкам и multimodal retrieval можно использовать как дополнительный candidate source или feature source. Fusion с текстовым поиском и structured filters должен происходить до или внутри ranker, но hard constraints пользователя - гео, цена, тип объекта, доступность - нельзя ломать из-за красивого embedding match.
Чат-ассистент - это UX-слой поверх поиска. Он может принимать запрос, задавать уточняющие вопросы, объяснять trade-offs и собирать shortlist из уже найденных real listings. Для RAG ему нужны retrieval results и verified listing facts, а не свободная генерация объявлений. Метрики: groundedness, фактологическая точность, task success, lead quality, latency и влияние на основные поисковые метрики.
Типичные ошибки
- Дать LLM генерировать объявления без grounding.
- Игнорировать галлюцинации про amenities или availability.
- Оценивать чат отдельно от leads, latency и качества поиска.
Как сказать на собеседовании
- Скажите: VLM enrichment offline, assistant grounded online.
- Назовите groundedness и consistency with listing facts как метрики.