Ask like a human: Implementing semantic search on Stack Overflow

David Haney31 Jul 2023

Problem

Stack Overflow search was lexical: it matched query keywords with TF-IDF in Elasticsearch. Such search is rigid: a misspelling or a synonym gives poor results, and a long conversational question may match no documents at all. Anything beyond a bag of keywords needs special punctuation and boolean operators.

Example from the article: for the query "how to sort list of integers in python", the old search put Swift array sorting and Apache Spark posts in its top 5. The semantic prototype returned five posts on sorting integer lists, four of them naming Python.

Solution in brief

Embed every question and answer as a vector and rank by cosine distance to the query vector. Keep lexical search beside it as a hybrid, because semantic search is weaker on short queries and exact tokens such as error codes. The prototype uses a pre-tuned open-source 768-dimension model and Weaviate.

Questions this case answers
  • How to move a keyword-based search over a large community-written text corpus to meaning-based retrieval while keeping exact-match behavior for rare tokens
  • How to pick the embedding model, text chunking and vector store for a semantic search prototype under open-source, self-hosted and Spark-integration requirements
  • How to let users search a Q&A site with full natural-language questions instead of keyword syntax?
  • How to add semantic search without losing exact matching for error codes and unique keywords?

Tools and methods

  • TF-IDF with stemming and bi-gram shingles (Elasticsearch) — lexical baseline.
  • Vector search by cosine distance — nearest-neighbor lookup between the query embedding and document embeddings.
  • Hybrid search — lexical and semantic ranking on the same data.
  • Sentence Transformers (pre-trained BERT) — generates the embeddings.
  • Azure Databricks and PySpark — pipeline feeding the embedding model.
  • Weaviate — open-source, self-hosted vector database with hybrid search and a native Spark connection.
Continue reading — it's free

Google or a one-time email code. No password.