Video in progress

For search in a product, do we write our own inverted index or bring in Elasticsearch/OpenSearch? How do you decide, algorithmically and organizationally?

An inverted index is algorithmically simple: word → list of documents, a query is an intersection of lists, and ranking is BM25. The hard parts are tokenization, morphology, updates, sharding and operations. If the data is small and queries are simple, PostgreSQL full-text search is enough; for complex search and large volume, a ready-made engine; writing our own, almost never.

📖 Answer

The algorithm at a glance:

  • split the document into tokens, lowercase, remove stop words, reduce to the stem;
  • term → sorted docId list (a posting list), stored compressed (delta + varint);
  • "java AND spring" is the intersection of two sorted lists, O(a+b) with two pointers; if one is very small, skip pointers or binary search in the larger one;
  • ranking: BM25, based on how often the word appears in the document (with saturation), how rare it is (IDF), and how long the document is.

You could write this in Java in a week. The problems come afterward:

  • The Uzbek language. Latin and Cyrillic, four different apostrophes for o', and suffixes: Uzbek words like kitoblarimizdan ("from our books"). Standard analyzers don't know Uzbek. This problem exists in a ready-made engine too, but there it's easy to plug in a plugin and a synonym dictionary.
  • Modifying an inverted index in place is expensive. Lucene solved this with segments and merges, which is really the LSM idea.
  • "jvaa" → "java": search with edit distance, done in Lucene with Levenshtein automata.
  • Facets, highlighting, autocomplete, shards, replicas, backups: all of that too.

My decision criteria:

  1. Volume and query type. Up to 1 million documents and plain keyword search: PostgreSQL tsvector + a GIN index, pg_trgm for typos. No new infrastructure, and transactional consistency comes free.
  2. Does relevance matter to the business? If so, Elasticsearch/OpenSearch: configurable analyzers, boosting, the explain API.
  3. Operational cost. An ES cluster means separate memory, version upgrades, index schema migrations, and syncing with the DB (CDC or outbox). Who on the team will carry this?
  4. Writing our own is only for very special cases: a small, in-memory, immutable corpus (say, search over the 5,000 questions inside the app), or using Lucene directly as a library.

I usually propose starting with PostgreSQL and migrating when search quality and volume measurements reach a clear threshold, with that threshold written down in advance.