Sub topic 5
Choosing a search engine
This chapter assumes you know why a system needs search at all, which the earlier chapters on when to add search and on inverted indexes cover. It also assumes you know basic SQL, REST APIs, and the idea of horizontal scaling. Here you compare the engine options and pick one with stated criteria. The choice affects index design, scaling, and operations in the chapters that follow.
The options fall into four groups
Search engines differ less in features than in who runs them and how far they scale. Most candidates fit one of these groups.
- Database full-text search. PostgreSQL (
tsvectorwith GIN indexes), MySQL (FULLTEXTindexes), and SQL Server all ship with one. The index lives inside your primary database. - Embedded libraries. Apache Lucene is the core library behind Elasticsearch, OpenSearch, and Solr. You can embed it directly in a JVM service. Few teams do, because you then own sharding, replication, and APIs yourself.
- Self-managed distributed engines. Elasticsearch, OpenSearch, and Apache Solr (all Lucene-based), plus lighter engines such as Typesense and Meilisearch. You run the cluster.
- Hosted search services. Elastic Cloud, Amazon OpenSearch Service, and Algolia. The provider runs the infrastructure, and you pay for it in money and reduced control.
The groups are not exclusive. Hosted Elasticsearch is both group 3 technology and group 4 operations.
Database full-text search
If your data already lives in PostgreSQL, the cheapest search service is the one you do not deploy. The example below creates a weighted, indexed search column and ranks results.
CREATE TABLE products (
id bigint PRIMARY KEY,
name text NOT NULL,
description text NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', name), 'A') ||
setweight(to_tsvector('english', description), 'B')
) STORED
);
CREATE INDEX products_search_idx ON products USING GIN (search);
SELECT id, name, ts_rank(search, query) AS rank
FROM products, websearch_to_tsquery('english', 'running shoes') AS query
WHERE search @@ query
ORDER BY rank DESC
LIMIT 10;The GIN index is an inverted index, so the query uses the same mechanism you studied earlier. The strengths are practical:
- No sync pipeline. The index updates in the same transaction as the row, so there is no staleness.
- One system to back up, secure, and operate.
- You can join search results with other tables and filter with ordinary SQL.
The limits show up as the feature grows:
- Ranking is basic.
ts_rankscores from term frequency and weights inside one row. It does not use corpus-wide statistics such as inverse document frequency, so it is not BM25. Rare terms are not favored over common ones. - Fewer language tools. Fuzzy matching, synonyms, and typo tolerance need extensions such as
pg_trgm, and they are awkward to combine with ranking. - Facets are expensive. Counting results per category over a large match set means scanning many rows.
- Search load competes with transactions. Heavy search queries share CPU, memory, and I/O with your writes. A read replica helps, but it scales vertically and by copying the whole dataset.
- No built-in sharding of the text index. Spreading one index over many machines means partitioning tables yourself.
Dedicated search engines
Distributed engines are built around the inverted index. Their features answer the limits above:
- BM25 scoring by default, with per-field boosts and tunable parameters.
- Analyzers per field and per language, synonyms, stemming, and fuzzy matching.
- Aggregations for facets, computed from columnar structures built at index time.
- Shards and replicas as first-class concepts, so the index can outgrow one machine.
- Near-real-time indexing, where new documents become searchable after a short refresh interval (about one second by default in Elasticsearch).
The costs are equally concrete:
- The engine is a second copy of your data. You must build and monitor the sync pipeline, and you must handle the delay between a database write and a searchable document.
- It is not a database. Do not treat it as the source of truth. Transactions, multi-document consistency, and durability guarantees are weaker than in a relational database.
- Cluster operations are real work. Shard sizing, heap and memory tuning, rolling upgrades, and snapshots all need an owner.
- Reindexing is part of life. Many mapping changes require building a new index, as a later chapter shows.
Comparing the main candidates
The table summarizes typical trade-offs. Treat it as a starting point and verify against current versions and your workload.
| Option | Best fit | Scales out | Relevance control | Operational load |
|---|---|---|---|---|
| PostgreSQL full-text | Small to mid catalogs, search tied to relational data | Replicas only, no index sharding | Low (weights, no IDF) | Lowest, nothing new to run |
| Elasticsearch / OpenSearch | Complex queries, facets, logs plus search, large data | Shards and replicas | High (BM25, scripts, boosts, rescoring) | High if self-run |
| Solr | Mature Lucene deployments, strong faceting | Shards and replicas (SolrCloud) | High | High |
| Typesense / Meilisearch | Product search and autocomplete with fast setup | Limited; smaller datasets, often in memory | Medium | Low to medium |
| Algolia (hosted) | Teams that want typeahead and ranking without running infrastructure | Managed by the vendor | Medium, via configuration | Lowest, but cost grows with usage |
Elasticsearch and OpenSearch share a common ancestor. OpenSearch is a fork from Elasticsearch 7.10, made after Elastic changed its license. Their APIs overlap heavily but have diverged since. If licensing matters to your organization, read the current terms for the version you plan to use.
Decision criteria
Work through these questions roughly in order. Stop when an answer settles the choice.
- How much data, and how fast does it grow? A few hundred thousand documents of modest size usually fit database full-text search comfortably. Hundreds of millions of documents, or an index larger than one node's memory and disk, point to a distributed engine.
- How good must relevance be? If "contains the words, newest first" is acceptable, a database is enough. If ranking quality drives revenue, as in e-commerce, you need BM25, boosts, synonyms, and the ability to tune and evaluate.
- What query features are required? Facets with counts, typo tolerance, prefix matching, geo filters, and highlighting are the usual deciders. Each one is possible in a database but costly to build.
- What freshness is required? A database index is consistent with the data at commit time. A separate engine adds seconds of delay at best. If users must see their own write immediately, you must design around it.
- Who will operate it? A three-person team with no cluster experience should weigh a managed service heavily. Running a production Elasticsearch cluster is a part-time job.
- What are the compliance and data-residency constraints? Hosted vendors hold copies of your data. Check whether that is allowed, and how access control is enforced.
- What does it cost at your query volume? Per-request pricing (common for search-as-a-service) and per-node pricing (common for managed clusters) scale differently.
Failure modes of a poor choice
Each wrong choice fails in a recognizable way.
- Staying on the database too long. Symptoms are search queries that dominate slow-query logs,
LIKE '%term%'scans, and relevance complaints you cannot fix. Migration is then urgent and happens under load. - Adopting a cluster too early. A small team runs a three-node cluster to search 50,000 rows. Most of the effort goes to sync bugs and upgrades, and the feature gains nothing.
- Using the engine as the primary store. After a bad mapping change or a lost node, there is no authoritative copy to rebuild from.
- Ignoring lock-in. Hosted services such as Algolia use proprietary query and ranking configuration. Moving later means rewriting queries and re-tuning relevance. Lucene-based engines make migration easier, though still not free.
- Choosing by benchmark alone. Published benchmarks rarely match your documents, query mix, and filters. Test with a sample of real data and real queries.
A pragmatic path
A common progression avoids both extremes:
- Start with database full-text search behind a small interface in your code, such as
search(query, filters, page). - Measure query latency, relevance complaints, and the load search puts on the primary database.
- When thresholds are crossed, add a dedicated engine behind the same interface and run both for a while, comparing results.
The interface is what keeps the switch cheap. Callers depend on your search contract, not on an engine's query language.
What this choice decides next
The engine you pick determines the vocabulary of the next chapters. Mapping syntax, analyzer names, shard settings, and refresh behavior differ per engine. The examples in this tutorial use Elasticsearch-style APIs because OpenSearch, and to a lesser extent other engines, share the concepts. The ideas transfer even when the syntax does not.
Exercise
A team runs an internal wiki with 200,000 pages in PostgreSQL. Users want keyword search with results ranked by relevance, and a page edit must appear in search results immediately after saving. Two engineers maintain the system and none has run a search cluster. Which option fits best, and which single requirement change would make you reconsider?
Show answer
PostgreSQL full-text search with a GIN index fits best. The data is small, the index updates in the same transaction as the edit (so freshness is immediate), and nothing new needs operating. Reconsider if relevance requirements grow beyond what ts_rank offers (for example typo tolerance, synonyms, or BM25-quality ranking), or if the data grows to a size where search load hurts the transactional workload. Either would justify a dedicated or managed engine behind the same search interface.
Exercise
Name two reasons a dedicated search engine should not be the only copy of your data, and say what you must be able to do as a result.
Show answer
First, it has weaker durability and transaction guarantees than a database. Second, mapping changes often require building a new index. Because of both, you must be able to rebuild the entire index from the source of truth at any time.