1---
2name: elasticsearch
3description: Query and index Elasticsearch with proper mappings, analyzers, and search patterns.
4metadata:
5 source: https://skillmd.com/skills/modbender/elasticsearch
6 clawdbot:
7 emoji: 🔍
8 requires:
9 anyBins:
10 - curl
11 os:
12 - linux
13 - darwin
14 - win32
15---
16
17## Mapping Mistakes
18
19- Always define explicit mappings—dynamic mapping guesses wrong (first "123" makes field integer, later "abc" fails)
20- `text` for full-text search, `keyword` for exact match/aggregations—using text for IDs breaks filters
21- Can't change field type after indexing—must reindex to new index with correct mapping
22- Set `dynamic: "strict"` to reject unmapped fields—catches typos in field names
23
24## Text vs Keyword
25
26- `text` is analyzed (tokenized, lowercased)—"Quick Brown" matches search for "quick"
27- `keyword` is exact bytes—"Quick Brown" only matches exactly "Quick Brown"
28- Need both? Use multi-field: `"title": { "type": "text", "fields": { "raw": { "type": "keyword" }}}`
29- Sort/aggregate on `title.raw`, search on `title`
30
31## Query vs Filter Context
32
33- Query context calculates relevance score—expensive, use for search ranking
34- Filter context is yes/no—cacheable, use for exact conditions (status, date ranges)
35- Combine: `bool.must` for scoring, `bool.filter` for filtering without scoring
36- Range queries on dates/numbers almost always belong in filter, not query
37
38## Analyzers
39
40- `standard` analyzer lowercases and removes punctuation—fine for most text
41- `keyword` analyzer keeps exact string—use for codes, SKUs, emails
42- Language analyzers (`english`) stem words—"running" matches "run"
43- Test analyzer with `_analyze` endpoint before indexing—surprises in production hurt
44
45## Nested vs Object
46
47- Object type flattens arrays—`{"tags": [{"key":"a","val":1}, {"key":"b","val":2}]}` becomes `tags.key: [a,b], tags.val: [1,2]`
48- Flattened loses association—query `key=a AND val=2` incorrectly matches above
49- Use `nested` type to preserve object boundaries—requires `nested` query wrapper
50- Nested is expensive—avoid for high-cardinality arrays
51
52## Pagination Traps
53
54- `from` + `size` limited to 10,000 hits—deep pagination fails
55- `search_after` for deep pagination—requires consistent sort, typically `_id`
56- Scroll API for bulk export—keeps point-in-time view, but ties up resources
57- Don't use scroll for user pagination—search_after is correct choice
58
59## Bulk Operations
60
61- Never index documents one-by-one—use `_bulk` API, 5-15MB batches
62- Bulk format: newline-delimited JSON, action line then document line
63- Check response for partial failures—bulk can succeed overall with individual doc errors
64- Set `refresh=false` during bulk loads—refresh after batch completes
65
66## Performance
67
68- `_source: false` with `stored_fields` if you don't need full document—reduces I/O
69- Use `filter` for cacheable conditions—Elasticsearch caches filter results
70- Avoid leading wildcards (`*term`)—forces full scan; use `reverse` field for suffix search
71- `profile: true` shows query execution breakdown—find slow clauses
72
73## Sharding
74
75- Shard size 10-50GB optimal—too small = overhead, too large = slow recovery
76- Number of shards fixed at creation—can't reshard without reindexing
77- Replicas for read throughput and availability—set based on query load
78- Start with 1 shard for small indices—over-sharding kills performance
79
80## Index Management
81
82- Use index templates—new indices get consistent mappings and settings
83- Use aliases for zero-downtime reindexing—point alias to new index after reindex
84- ILM (Index Lifecycle Management) for time-series—auto-rollover, delete old indices
85- Close unused indices to free memory—closed index uses no heap
86
87## Aggregations
88
89- `terms` agg needs `keyword` field—text fields fail or give garbage
90- Default `size: 10` on terms agg—increase to get all buckets, or use composite
91- Cardinality is approximate (HyperLogLog)—exact count requires scanning all docs
92- Nested aggs require `nested` wrapper—matches nested query pattern
93
94## Common Errors
95
96- "cluster_block_exception"—disk > 85%, cluster goes read-only; clear disk, reset with `_cluster/settings`
97- "version conflict"—concurrent update; retry with `retry_on_conflict` or use optimistic locking
98- "circuit_breaker_exception"—query uses too much memory; reduce aggregation scope
99- Mapping explosion from dynamic fields—set `index.mapping.total_fields.limit` and use strict mapping