All searches are reads, but not all reads are searches. Understanding this distinction is key to designing scalable systems.
| Type | Example | Optimized By |
|---|---|---|
| Point lookup | Get book by ID | Primary key index |
| Range query | Books published 2020-2024 | B-tree index |
| Search | Books with "architecture" in title | Inverted index |
| Aggregation | Count books by author | Column stores, pre-computed |
GET /books/book-123
→ Direct hash lookup, returns immediately
The database knows exactly where the data lives. Like looking up a word in a dictionary when you know the exact spelling.
GET /books?title_contains=architecture
→ Must find all matching documents
→ Rank by relevance
→ Return sorted results
The database must find all matches, score them, and return sorted results. Like asking "find all words related to 'happy'" - requires understanding meaning, not just location.
Firestore Query: "Find books where title contains 'architecture'"
┌─────────────────────────────────────────────────┐
│ Firestore has NO inverted index │
│ │
│ It must scan documents sequentially: │
│ Doc 1 → check title → no match │
│ Doc 2 → check title → no match │
│ Doc 3 → check title → MATCH │
│ ... │
│ Doc 100,000 → check title → no match │
│ │
│ O(n) complexity - gets worse with more data │
└─────────────────────────────────────────────────┘
Firestore limitations:
- No native full-text search
whereonly supports exact matches,>=,<=,array-contains- Can't search "contains" or "like" efficiently
- Compound queries require composite indexes (and you hit index limits)
- Read costs scale with result set size
Elasticsearch uses an inverted index - it pre-processes text and maps terms to documents:
Term → Documents
"domain" → [doc1, doc5, doc12]
"driven" → [doc1, doc5]
"design" → [doc1, doc3, doc8, doc12]
"architecture"→ [doc2, doc7, doc15, doc23]
When you search for "architecture":
- Look up term in index → O(1)
- Get document IDs → [doc2, doc7, doc15, doc23]
- Fetch and rank documents → O(k) where k = matches
No scanning required.
┌─────────────────┐
│ PostgreSQL │
│ │
Writes ───────────→ │ • Point reads │ ← Simple reads
│ • Range queries│
└─────────────────┘
│
sync
▼
┌─────────────────┐
Searches ─────────→ │ Elasticsearch │
│ │
│ • Full-text │
│ • Fuzzy match │
│ • Aggregations │
└─────────────────┘
-- Point lookup (O(1))
SELECT * FROM books WHERE id = 'abc';
-- Range query (O(log n))
SELECT * FROM books WHERE created_at > '2024-01-01';
-- Simple filter (O(log n) with index)
SELECT * FROM books WHERE author_id = 'xyz';// Full-text search
{ "query": { "match": { "title": "software architecture" } } }
// Fuzzy matching (typo tolerance)
{ "query": { "fuzzy": { "title": "architekture" } } }
// Aggregations
{ "aggs": { "by_author": { "terms": { "field": "author" } } } }
// Complex boolean queries
{
"query": {
"bool": {
"must": { "match": { "title": "architecture" } },
"filter": { "term": { "available": true } },
"should": { "match": { "description": "patterns" } }
}
}
}| Query Type | Use PostgreSQL | Use Elasticsearch |
|---|---|---|
| Get by ID | Yes | No |
| Get by foreign key | Yes | Maybe |
| Date range filter | Yes | Maybe |
| Full-text search | No | Yes |
| Autocomplete | No | Yes |
| Typo tolerance | No | Yes |
| Relevance ranking | No | Yes |
| Faceted search | No | Yes |
| Complex aggregations | Maybe | Yes |
┌──────────────┐ writes ┌──────────────┐
│ Firestore │ ────────→ │ Cloud │
│ (primary) │ trigger │ Function │
└──────────────┘ └──────┬───────┘
│ index
▼
┌──────────────┐ search ┌──────────────┐
│ App │ ←───────→ │Elasticsearch │
│ │ │ (Algolia) │
└──────────────┘ └──────────────┘
Common solutions:
- Algolia - Managed search, easy Firebase integration
- Elasticsearch - Self-hosted, more control
- Typesense - Open-source Algolia alternative
- Meilisearch - Fast, simple to deploy
Simple reads can stay on the write database, but complex searches benefit from a dedicated read model optimized for that access pattern. This is the essence of CQRS - use the right tool for each type of operation.
List queries have one stable order in both stores:
| Read | Order |
|---|---|
| Books | title ASC, id ASC |
| Patrons | registered_at ASC, id ASC |
| Patron loans | borrowed_at DESC, id ASC |
| Overdue loans | due_date ASC, id ASC |
The ID tie-breaker is mandatory; sorting by a non-unique field alone can skip
or duplicate rows between pages. Offset pagination is supported only inside a
bounded 10,000-result window. Large or changing result sets use the opaque,
filter-scoped cursor returned in X-Next-Cursor. The cursor is also pinned to
the backend that produced its sort tuple. A first page can fall back from
Elasticsearch to PostgreSQL, but an in-progress Elasticsearch page returns a
temporary availability error if Elasticsearch disappears; it never applies an
Elasticsearch sort tuple under a potentially different database collation.
When Elasticsearch is unavailable, title/author substring search falls back
to PostgreSQL ILIKE with user wildcard characters escaped. The baseline
schema includes pg_trgm GIN indexes for this exact operator shape; ordinary B-tree
indexes do not accelerate a leading-wildcard predicate.
"Overdue" is never stored as a durable boolean. It means status NOT IN (returned, cancelled) AND due_date < now and is evaluated at request time in
both Elasticsearch and PostgreSQL, so a loan becomes overdue even when no
row-change event occurs. Likewise, only_active means every outstanding loan,
including records already classified as overdue or lost.