elasticsearch
Scope
Covers Elasticsearch itself: index and mapping design, text analysis, the Query DSL, ES|QL, relevance and its measurement, aggregations, vector and semantic retrieval, data streams and the index lifecycle, reindexing, shard and heap capacity, cluster allocation, diagnostics, and cluster-level security.
The body is written against Elasticsearch 9.5 (9.5.3 at time of writing; 8.19 is the last 8.x
series). Rules that need a particular version carry a gate such as (9.4+). Facts marked as
measured were run against a single-node 9.5.3 instance on a basic licence.
Not covered:
- Relational schema, SQL and plan tuning. Use the
postgresskill. - Document-database modelling and aggregation pipelines in MongoDB. Use the
mongodbskill. - Key-value caching, expiry and eviction. Use the
redisskill. - Log and metric collection pipelines, agents and shippers, alerting rules, SLOs, and working back
from a production alert to a code path. Use the
observabilityskill. Index and query design for data that happens to be logs is in scope; getting the logs there and paging someone about them is not. - Kibana: dashboards, Lens, Discover, saved objects, Agent Builder, workflows. Not covered by any skill here.
- Managed control planes — Elastic Cloud provisioning, deployment sizing, AWS OpenSearch Service
domains, billing and autoscaling APIs. The index- and query-level rules still apply on managed
hosting; node settings,
elasticsearch.ymland JVM options usually will not. - OpenSearch-only APIs. It forked from 7.10 and has diverged:
neuralqueries, ml-commons, search pipelines and PPL do not exist here, and advice written for one is not valid for the other without checking.
Paths below are relative to this skill's directory.
Core rules
- Establish the version and the licence tier before quoting a rule or designing anything:
GET /andGET /_license. Half the guidance in circulation is written for 7.x, and several headline retrieval features are above the basic tier. - Read the mapping before proposing a query, and the access patterns before proposing a mapping
(
GET /{index}/_mapping). Both directions of guessing produce work that cannot be undone without a reindex. textmatches,keywordfilters. Atextfield is analysed into tokens and atermquery is not analysed, sotermontextreturns HTTP 200 with zero hits and no error anywhere.- Aggregate and sort on
keyword, never ontext. The failure isFielddata is disabled on [f]; the fix is the.keywordsub-field. Settingfielddata: trueuninverts every distinct term into heap and is the most reliable way to break a cluster. - A
keywordsub-field on a long text body needsignore_above, or the whole string is indexed as one term. A field that is only searched should not have the sub-field at all. - Dynamic mapping guesses from the first document, and the guess is permanent. Measured on 9.5.3
a JSON string becomes
textplus akeywordsub-field withignore_above: 256, and9.99becomesfloat, notdouble. Prefer explicit mappings with"dynamic": "strict". - Mappings are append-only. Adding a field is fine; changing a field's type, analyzer,
indexordoc_valuesflag is impossible in every version. The path is new index →_reindex→ alias swap, which is why every index that matters is created behind an alias on day one. - A dynamic
objectover unbounded keys (Kubernetes labels, headers, experiment buckets) becomesLimit of total fields [1000] has been exceeded. Map itflattened. Raisingindex.mapping.total_fields.limitpostpones the outage and grows cluster state. - If dropping a clause would change which documents come back rather than their order, it
belongs in
bool.filter. Filter context skips scoring and is cacheable; the rewrite never changes the result set. - An object array flattens and loses per-item association. Measured: with
usersasobject, filteringusers.first: Aliceandusers.last: Jonesmatches a document containing Alice Smith and Bob Jones. Usenestedonly when a query must combine two fields of one element. - A leading
*cannot use the term dictionary. Measured, awildcard: "*ctiv*"profiles 47× slower than the equivalentTermQueryon a one-document index. Usematchon the analysed field, thewildcardfield type, or index-time ngrams. - An analyzer that adds tokens (
edge_ngram, index-time synonyms, shingles) must not run at search time. Measured, anedge_ngramanalyzer turns the queryelasticinto[el, ela, elas, elast, elasti, elastic], so everything matches everything. Setsearch_analyzer: standard. from + sizebeyondindex.max_result_window(10 000) is a hard error, and every page below it makes each shard sort and shipfrom + sizehits. User-facing paging issearch_afterplus a point-in-time; exports are PIT scans or_reindex.- A
sortclause replaces relevance ordering entirely. When every_scoreis 1.0 ornull, no boost anywhere in the query can change anything — remove the sort before tuning relevance. - Query rules pin documents; boosts rank them. Creating a ruleset pins nothing: the search body
must carry a
rulequery whosematch_criteriasupplies every metadata key the criteria use. - Every
termsaggregation is approximate. Reportdoc_count_error_upper_boundandsum_other_doc_countalongside the buckets; usecompositewhen the requirement is to enumerate everything rather than to rank the top N. cardinalityandpercentilesare estimates (HyperLogLog++ and TDigest). Percentiles are not additive — never average a p99 across shards, days or services.dense_vectoris quantized by default in 9.x. Measured:int8_hnswup to 320 dimensions,bbq_hnswwithrescore_vector.oversample: 3.0from 384 up. Recall is a number you measure against exact search, not an assumption; the query-side knob isnum_candidatesand there is noef_search. Vectors are also excluded from_sourceby default (index.mapping.exclude_source_vectors), so code reading an embedding back out of a hit silently gets nothing.- The Inference API and the
rrfandlinearretrievers are Enterprise-tier: measured, all three return HTTP 403current license is non-complianton a basic licence. So on basic there is no in-cluster embedding, no ELSER, no semantic reranking and no fusion operator — embed outside the cluster, and fuse with aknnclause beside amatchclause inbool.should, or by reciprocal rank in the application. - Licence failures for inference are delayed: a
semantic_textmapping is accepted andGET /_inference/_alllists the preconfigured endpoints, and only the first document indexed returns the 403. Prove a gated feature end to end, not by creating the index. - Shard count comes from data volume:
max(1, ceil(primary_gb / target_shard_size_gb))with a 10–50 GB target, never from node count. Budget 20 shards per GB of heap; the hard stop iscluster.max_shards_per_node(1000, replicas counted). - Heap is
min(RAM/2, 31g). The other half is the page cache Lucene reads from, and above roughly 32 GB the JVM loses compressed object pointers, so 48 GB of heap addresses fewer objects than 31 GB. - Yellow means a replica is unassigned — degraded redundancy, not data loss. Red means a primary
is unassigned. On a single node, yellow is the expected state.
unassigned_info.reasonis the trigger; the decider withdecision: "NO"in_cluster/allocation/explainis the cause. search_phase_execution_exceptionis a wrapper: the real error is infailed_shards[].reason. A_bulkrequest likewise returns HTTP 200 while individual items fail, so branch on the response'serrorsflag every time — andes_rejected_execution_exceptionis the ceiling you were looking for, not a transient to retry harder against.- Finish with evidence: re-run under
"profile": trueand quote the top node before and after, or re-run_rank_evalagainst the judgement set and quote the metric. Atookthat moved without the profile changing is a warm cache.
Workflows
design-or-review-a-mapping
- Collect the access pattern per field — searched as prose, filtered exactly, aggregated,
sorted, or only returned. Missing access patterns are a blocker, not a guess
(
references/mapping-and-types.md). - Assign the minimal type set:
textfor prose,keywordfor exact, the multi-field only when one logical field is genuinely both,flattenedfor unbounded key spaces,scaled_floatfor bounded-precision metrics,ip/version/datewhere they apply. - Strip waste:
doc_values: falseon return-only fields, no.keywordon fields nobody facets,ignore_aboveon everykeywordsub-field of a long body. - Decide the dynamic policy explicitly —
strictfor anything user-facing,runtimewhen new fields must remain queryable without being indexed. - Check the array-of-objects fields: does any query need two of their fields to match the same
element? Only then is
nestedjustified. - Settle the analysis chain and check the index/search asymmetry for anything that expands
tokens (
references/analysis.md). - Decide index shape: time-based append-only data is a data stream with rollover, not a hand-
rolled daily index; everything else is an ordinary index behind an alias
(
references/data-lifecycle.md). - Gate — the mapping does what you said: create it on a scratch index, index one real
document, then
GET /{index}/_mappingto confirm nothing was inferred, run oneterm, one aggregation and one search against the fields you claimed support them, and confirm each works.
fix-a-query-that-returns-the-wrong-documents
-
GET /{index}/_doc/{id}— does the document exist? If not, this is ingest, not search (references/diagnostics.md). -
GET /{index}/_validate/query?explain=true— does it parse and rewrite to what you meant? -
POST /{index}/_analyzeon the field and on the query text — are the terms the same terms? This is wheretermontextand the index/search analyzer mismatch both surface. - Check the mapping for every field the query names: a clause on a sub-field that does not exist matches nothing, silently, whatever its boost.
-
GET /{index}/_explain/{id}with the query body for one document that should have matched — it names the failing clause. - Check
boolsemantics:shouldbeside amustis optional,must_notalone matches everything else,minimum_should_matchis not what you assumed (references/query-dsl.md). - Gate — the failing case passes: re-run the original query, show the document in the hits, and show that the documents that should not match still do not.
tune-relevance
- Remove anything that overrides scoring first — a
sortclause,constant_score, an all-filter query. Every_scoreat 1.0 means nothing downstream can help (references/relevance.md). - Build a judgement set before changing anything: 30–50 real queries from the log, graded 0–3,
plus the queries behind the last few complaints. Record the baseline with
_rank_eval. - Fix structure before boosts: filters out of
must,multi_matchacross the right fields with a deliberatetype,minimum_should_matchstated. - Read one bad result with
"explain": true— idf that shows the term is in most documents, or a length norm that is doing the ranking, changes what you would have boosted. - Apply one lever at a time: field boosts for importance,
rank_featurefor popularity,distance_featureor a decay for recency, query rules for "this document must be first". - Consider a second phase only after the first is right:
rescorewith a phrase query, or atext_similarity_rerankerover the top N. - Gate — the metric moved: re-run
_rank_evalwith the same judgement set and quote nDCG@10 before and after. A change with no number is a guess.
diagnose-a-slow-search
- Separate slow from blocked:
GET /_cluster/healthandGET /_cat/thread_pool/search,write. Rememberrejectedis cumulative since node start — take two samples (references/diagnostics.md). - Run the real query with
"profile": trueand name the top node bytime_in_nanos. Do not propose capacity changes before this exists. - Read the
breakdown:next_docdominating is iteration (a wildcard, a scan);rewrite_timeis term enumeration;build_scoreris a huge clause list. - Apply the rewrite the profile points at: leading wildcard →
matchon the analysed field; non-scoring clauses →filter;matchon akeyword→term; unroundednow→ rounded date maths so the request cache can work (references/query-dsl.md). - Check what the response carries:
sizelarger than anyone reads, unfiltered_source,track_total_hits: true, deepfrom. - Only now look at shape: shard count against data volume, heap against the 31 GB ceiling,
shards per node against the budget (
references/cluster-operations.md). - Gate — the profile changed: re-run with
"profile": true, quote the old and new top node and theirtime_in_nanos, and say explicitly if the result set changed.
add-vector-or-hybrid-search
-
GET /_licensefirst. On basic the Inference API, therrfretriever and thelinearretriever are all 403, so there is no in-cluster embedding and no fusion operator, and the design has to embed outside the cluster and fuse by hand (references/vector-and-semantic-search.md). - Choose the method against the corpus: BM25 for exact and rare terms, ELSER or dense vectors for paraphrase, hybrid when both matter — which is most of the time.
- Where inference is available, prefer
semantic_textunless you need a specific model, chunking strategy or quantization setting; it handles chunking, embedding and query embedding. Confirm ML-capable nodes exist, and confirm the licence by indexing one document rather than by creating the index — the mapping is accepted either way. - For explicit
dense_vector: pindimsto the model, matchsimilarityto how the vectors were produced, read the mapping back to see which quantization you actually got, and decide whetherexclude_source_vectorsneeds turning off. - Put the filter inside the
knnclause, not around it, so thekresults are all filtered documents. - Fuse:
rrfretriever on Enterprise; on basic aknnclause and a lexical clause insidebool.shouldwith boosts that you tune, or reciprocal-rank fusion in the application. - Gate — recall and relevance are numbers: measure approximate-versus-exact overlap@k for
the vector side, and nDCG@10 with
_rank_evalfor the fused result. Raisenum_candidatesuntil recall plateaus.
change-a-mapping-on-a-live-index
- Classify the change: additive (a new field, a new multi-field) applies in place; anything
touching an existing field's type, analyzer,
indexordoc_valuesneeds a new index (references/data-lifecycle.md). - For a data stream, check whether a manual rollover is enough — new fields land in the new backing index and old data stays readable, with no reindex at all.
- Create the destination with the complete corrected mapping,
number_of_replicas: 0andrefresh_interval: -1for the copy. -
POST /_reindexwithwait_for_completion=falseand"slices": "auto"; keep the task id and read the task'sfailuresarray rather than assuming success. - Decide how writes arriving during the copy are handled — dual write, or a second delta reindex bounded by timestamp.
- Restore replicas and refresh interval, compare
_counton both sides, then swap the alias in onePOST /_aliaseswithremoveandaddtogether. - Gate — proven from the application's side: run the application's real queries against the alias, confirm counts and top hits match the old index, and only then delete the source.
Topic router
| Topic | Read when | File |
|---|---|---|
Access-pattern-to-type table, dynamic mapping's actual output, multi-fields and ignore_above, object/array/nested/join, flattened, doc_values/index/_source modes, runtime fields, the hard limits, index and component templates, why a type change needs a reindex | Designing or reviewing a mapping, or deciding how to store something | references/mapping-and-types.md |
The analysis chain, index versus search analyzer, autocomplete without breaking search, synonyms, per-language fields, keyword normalizers, _analyze and _termvectors | A query matches nothing, matches everything, or autocomplete behaves oddly | references/analysis.md |
Filter context and caches, bool semantics, the query-type table with traps, wildcards and prefixes, pagination and point-in-time, _source/fields/docvalue_fields, percolator, the verification ladder | Writing or reviewing a Query DSL body | references/query-dsl.md |
BM25 and its knobs, multi_match types, boosting that works, rescore and semantic reranking, query rules wiring, _rank_eval and judgement sets, reading an explain tree | Results rank badly, or a relevance change needs proving | references/relevance.md |
Bucket/metric/pipeline families, terms error bounds, composite, cardinality and percentiles as estimates, date histograms and time zones, nested aggregations, bucket limits and breakers, the field-type mistakes | Building or debugging aggregations, or explaining why the numbers disagree | references/aggregations.md |
The licence gate, retrieval-method comparison, dense_vector defaults and quantization, kNN and filters, semantic_text, ELSER, hybrid on basic and on Enterprise, chunking, measuring recall | Adding semantic, vector or hybrid retrieval | references/vector-and-semantic-search.md |
When ES|QL beats Query DSL, query shape, the implicit LIMIT 1000, the command table, full-text functions and METADATA _score, LOOKUP JOIN versus ENRICH, FORK/FUSE, TS, SET directives, DSL-to-ES|QL translation | Writing an analytical query, or translating one | references/esql.md |
Aliases and atomic swaps, data streams and their create-only rule, rollover conditions, ILM versus the data-stream lifecycle, index modes including logsdb, the reindex procedure, bulk indexing, ingest pipelines, snapshots | Setting up time-based data, changing a mapping, or loading in bulk | references/data-lifecycle.md |
| The shard-count formula, heap rules, node roles, allocation deciders, disk watermarks, thread pools, circuit breakers, refresh/flush/merge, rolling restarts and version compatibility, authentication and API keys | Sizing a cluster, or a shard will not allocate | references/cluster-operations.md |
| The triage ladder, reading a profile, the exception-to-cause table, the cluster-status call set, slow logs, isolating query cost from node cost, benchmarking honestly | Something is slow, failing, or yellow, and you need the cause | references/diagnostics.md |
Output format
When reviewing a mapping, a query or a cluster change, group findings by file and lead each with the location:
events-mapping.json:31 - breaking - `labels` is a dynamic object over unbounded k8s keys, so every new key becomes a mapped field; this is the source of `Limit of total fields [1000] has been exceeded`. Map it `flattened`; raising the limit grows cluster state instead of fixing it.
Order findings by blast radius: things that already fail or lose data first, then things that require a reindex to fix later, then performance, then style. Separate the two classes explicitly — what can be applied to the live index, and what needs a new index plus reindex plus alias swap — because that distinction decides the release plan.
For a performance finding, quote the evidence (time_in_nanos and node type from the profile,
doc_count_error_upper_bound, the exception's failed_shards[].reason) rather than asserting that
something is slow, and give the before and after request bodies.
Environment
- Reproduce against the same minor version as production, and say so when you cannot. Defaults
move within a major: which quantization a
dense_vectorgets, whether vectors stay in_source, and which features the licence gates have all changed inside 9.x, so a finding from 9.1 is not a finding about 9.5. A single node is enough for mapping behaviour, analysis, query semantics, profile shapes and licence gates:docker run --rm -p 9200:9200 -e discovery.type=single-node -e xpack.security.enabled=false docker.elastic.co/elasticsearch/elasticsearch:9.5.3. Expect yellow — the replica has nowhere to go — and setnumber_of_replicas: 0if that is in the way. GET /_licensedecides which retrieval features exist, and the check has to exercise the feature: asemantic_textmapping is accepted on any tier andGET /_inference/_alllists the preconfigured endpoints on any tier, but indexing a document returns403 ... [inference]below Enterprise.semantic_text, ELSER and reranking additionally need ML-capable nodes, independently of the licence.- On Elastic Cloud Serverless (
build_flavor: "serverless"inGET /), shard, node, allocation and JVM settings do not exist and version numbers must not be used for feature checks. - Anything written for OpenSearch needs re-verifying here: the APIs diverged after the 7.10 fork.


