Sub topic 6
Designing the index and its mapping
This chapter assumes you know what an inverted index is and how text analysis turns raw text into terms. It also assumes you can read a basic SQL schema. The examples use Elasticsearch-style syntax. OpenSearch is nearly identical, and Solr and others use the same ideas under different names.
By the end you should be able to turn a relational table into a search document. You should also be able to pick a field type for each column and explain why some mapping decisions are expensive to undo.
What an index and a mapping are
An index is the search engine's equivalent of a table. It holds documents, which are JSON objects, and every document is searchable through the same inverted structures.
A mapping is the index's schema. It lists each field and says how the engine should treat it. The mapping controls three things:
- Whether a field is analyzed into terms (full text) or stored as one exact value.
- Which data structures the engine builds for the field, such as an inverted index for matching, or column-oriented values for sorting and aggregations.
- How values are parsed, for example as a number, a date, or a boolean.
Query behavior follows from these choices. A query that works on one field type can return nothing, or the wrong thing, on another.
Start from the queries, not the table
A database schema is designed around the data and its integrity. A search mapping is designed around the questions users will ask. Before writing a mapping, list the queries and sort each into one of these groups:
- Text the user types, which needs full-text matching and relevance scoring.
- Narrowing conditions, such as category, price range, or availability, which need exact matching.
- Orderings and groupings, such as sort by price or count by brand.
- Fields that are only returned for display.
Each group maps to different field types. A field can belong to more than one group, and the engine lets you index the same value in more than one way.
Text versus keyword
Most mapping mistakes involve the difference between these two types.
- A
textfield is passed through an analyzer. "Trail Running Shoes" becomes the termstrail,run,shoe, or similar, depending on the analyzer. You can match on any term, and the document gets a relevance score. You cannot reliably sort or aggregate on it. - A
keywordfield is stored as one unanalyzed term. "Footwear" staysFootwear, including its case. It supports exact matching, sorting, and aggregations. A search forfootwearin lowercase will not match.
Here is the mapping from the spine, which applies this rule:
PUT /products
{
"mappings": {
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "float" },
"in_stock": { "type": "boolean" }
}
}
}The product name is something people search, so it is text. The category is something people pick from a list, so it is keyword. Price and stock status are filters, so they get numeric and boolean types.
Multi-fields: one value, several indexes
Sometimes you need both behaviors from one value. Users search a product name as text, but you also want to sort alphabetically by name or count distinct names. A multi-field indexes the same source value twice under two names.
PUT /products-v2
{
"mappings": {
"dynamic": "strict",
"properties": {
"name": {
"type": "text",
"fields": {
"raw": { "type": "keyword", "ignore_above": 256 }
}
},
"description": { "type": "text" },
"sku": { "type": "keyword" },
"category": { "type": "keyword" },
"price": { "type": "float" },
"in_stock": { "type": "boolean" },
"updated_at": { "type": "date" }
}
}
}Queries use name for full-text matching and name.raw for sorting and exact matches. The source document stays the same, with one name value. The engine creates both representations. The cost is extra index size, so add multi-fields only where a query needs them. The ignore_above setting skips values longer than 256 characters for the keyword version, which keeps very long strings out of the exact-match structures.
Choosing types for common fields
| Source column | Typical search type | Reason |
|---|---|---|
| Title, description, body | `text` | Matched by words and scored by relevance |
| Category, brand, status, tag | `keyword` | Exact filters, facets, and sorting |
| SKU, user ID, email | `keyword` | Must match exactly, with no splitting |
| Price, rating, quantity | `float`, `integer`, `long` | Range filters and numeric sorting |
| Created and updated times | `date` | Range filters and recency sorting |
| Flags such as in stock | `boolean` | Cheap true or false filters |
| Phone number, ZIP code | `keyword` | You never do arithmetic on them, and leading zeros must survive |
Choose the smallest numeric type that fits your range. For money, many teams store integer minor units (cents) to avoid floating-point rounding, and convert for display.
Shaping the document
A search document is not a row. It is the thing a user wants to see in a result list, with everything needed to find and filter it.
Denormalize joins into the document
Relational databases split data across tables and join at query time. Search engines are poor at joins, so you flatten the data when you build the document. A product row plus its brand name and category path becomes one document:
{
"name": "Trail running shoes",
"brand": "Northpeak",
"category": "footwear",
"category_path": ["sports", "footwear", "running"],
"price": 89.0,
"in_stock": true
}The trade-off is duplication. If a brand is renamed, every product document carrying that name must be reindexed. That is acceptable when the duplicated data changes rarely. If it changes often, think hard before copying it into every document.
Decide the unit of a result
Ask what one result row represents. A product with ten variants could be one document with a list of variants, or ten documents grouped at query time. One document per product keeps result lists clean but makes per-variant filters such as "size 42 in red" tricky. Arrays of plain objects are flattened internally, so the engine can match "red" from one variant and "42" from another. The nested type keeps each object's fields together, at the price of more indexing and query cost. Use it only when you need correlated matches inside a list.
Keep the document ID stable
Use the primary key from the source database as the document ID. That gives the data sync pipeline a natural key for idempotent updates, which the next chapters build on.
Dynamic mapping and why to turn it off
By default, the engine guesses a type when it sees a new field. A string becomes text with a keyword sub-field, a whole number becomes long, and so on. This is convenient for experiments and risky in production:
- A typo in a field name silently creates a new field.
- The first value fixes the type. If
"price": "N/A"arrives first, the field may be mapped as text and range queries on price stop behaving. - Fields grow without limit if you index user-supplied keys, which bloats the mapping. The engine caps the total number of fields, and hitting that cap causes indexing errors.
Setting "dynamic": "strict", as in the example above, rejects documents that contain unmapped fields. The sync pipeline then fails loudly, which is usually better than quietly indexing bad data. A softer option is "dynamic": false, which keeps unknown fields in the stored source but does not index them.
Mappings are hard to change
You can add a new field to an existing mapping. You generally cannot change the type of an existing field, switch its analyzer, or convert text to keyword. Existing documents were indexed with the old structures, and the engine will not rebuild them in place.
The fix is to create a new index with the corrected mapping and copy the data across. Reindexing gets its own chapter. For design purposes, two habits make it painless:
- Name indexes with a version suffix, as in
products-v2, and point an alias such asproductsat the current one. The application queries the alias and never needs to change. - Keep the source of truth able to regenerate every document, so a rebuild never depends on the old index.
Analyzers per field
Text analysis settings live in the mapping, on each field. Product names might use a stemming analyzer so "running" matches "run". A brand field might use a lighter analyzer with no stemming, so "Nike" is not altered. Fields can also use a different analyzer at query time than at index time, which becomes important for autocomplete. Choose analyzers per field, based on how people search that field, not one global default.
Fields you only store
Not every field needs to be searchable. A large HTML body kept only for display can be left unindexed, or kept out of the document altogether and fetched from the database by ID. Smaller indexes are faster and cheaper to run. A common pattern is to return just IDs and scores from search, then load the full records from the primary store, so the index holds only what it needs to match, filter, sort, and rank.
How the pieces fit
Common mistakes
- Leaving everything to dynamic mapping, then discovering a field has the wrong type after millions of documents are indexed.
- Using
textfor fields that people filter by, which causes partial or missing matches. - Sorting on a
textfield. Add a keyword sub-field instead. - Copying fast-changing data into every document, which turns one update into thousands of reindex operations.
- Mirroring the relational schema one table per index, then trying to join at query time.
Exercise
A table has columns title, author_email, genre, page_count, and published_at. Users search by words in the title, filter by genre, sort by publication date, and look up all books by an exact author email. Give the mapping type for each column, and say where you would add a multi-field.
Show answer
title is text, since users search it by words. author_email is keyword, because it needs exact lookups and the analyzer must not split it. genre is keyword, for exact filters and facets. page_count is integer, and published_at is date, which supports sorting and range filters. Add a multi-field only if a query needs both behaviors from one value. For example, give title a title.raw keyword sub-field if you want to sort alphabetically by title. Otherwise no multi-field is needed.