Sub topic 2
Designing the Index and Its Mapping
Assume you know basic SQL, REST APIs, message queues, caching, and horizontal scaling. This chapter focuses on how a search index represents data and how applications keep it useful when the primary database changes.
Designing the index and its mapping
An index is a search-optimized copy of selected fields from the source database. Its mapping defines how each field is stored and queried.
Use analyzed full-text fields for words that users search naturally. Use exact-match fields for categories, identifiers, and status values.
| Field | Type | Typical use |
|---|---|---|
| `name` | `text` | Relevance-ranked word searches |
| `category` | `keyword` | Exact filters and facets |
| `price` | `float` | Numeric ranges |
| `in_stock` | `boolean` | Availability filters |
{
"mappings": {
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "float" },
"in_stock": { "type": "boolean" }
}
}
}A text field is analyzed into terms. A keyword field keeps its complete value. Mapping a category as text makes exact filtering unreliable because the value may be split into tokens.
Keeping the index in sync
The database remains the source of truth. Publish a change event after a successful database transaction, then consume that event to create, update, or delete the indexed document.
Use the source record's version or update timestamp. Idempotent indexing means processing the same event twice produces the same result. Version checks prevent an older, delayed event from overwriting newer data.
PUT /products/_doc/42?version_type=external&version=7
Content-Type: application/json
{
"name": "Trail running shoes",
"category": "footwear",
"price": 89.0,
"in_stock": true
}Living with eventual consistency
The index is usually eventually consistent. A successful database write may appear in search only after the event queue and indexing worker finish.
Design for this delay by showing the database result immediately after a write, retrying failed indexing, and monitoring queue age and indexing errors. A periodic reconciliation job can compare database records with indexed records.
Designing search queries
Keep relevance clauses separate from filters. Filters restrict results without changing their scores. Facets are grouped counts, such as the number of results in each category. Use stable pagination, preferably a cursor such as search_after, for deep result pages.
{
"query": {
"bool": {
"must": [{ "match": { "name": "running shoes" } }],
"filter": [
{ "term": { "category": "footwear" } },
{ "range": { "price": { "lte": 100 } } }
]
}
},
"size": 10,
"aggs": {
"categories": { "terms": { "field": "category" } }
}
}Exercise
Why should category usually be mapped as keyword rather than text?
Show answer
A keyword field preserves the complete value, which supports exact filters and facet counts.