Aggregations
What to know
Aggregations fall into three families. Metric aggregations (avg, sum, min, max, stats, value_count, cardinality, percentiles, top_hits, geo variants) compute numbers. Bucket aggregations (terms, date_histogram, histogram, range, filters, nested, reverse_nested, composite, significant_terms) group documents. Pipeline aggregations (derivative, cumulative_sum, moving_fn, bucket_script, bucket_selector, avg_bucket) compute over other aggregations' output. Send "size": 0 when you only want the numbers and no hits.
Traps
- A
termsaggregation on atextfield fails unlessfielddatais enabled - aggregate on thekeywordsub-field instead. termscounts are approximate and shard-local: readdoc_count_error_upper_boundandsum_other_doc_count, and raiseshard_size(orsize) when precision matters.cardinalityis approximate; raiseprecision_threshold(max 40,000) for small, high-accuracy sets.- Aggregating on nested fields requires a
nestedaggregation with the rightpath; returning to parent documents needsreverse_nested. - Pipeline aggregations reference siblings or children by name through
buckets_path, andbucket_selectorfilters buckets, not documents. - Paging past the first page of buckets needs
composite, nottermswith a largefrom.
Rule of thumb
Order terms buckets by a sub-aggregation ("order": {"avg_price": "desc"}) when "top by count" is not what the question means - and expect that ordering by a sub-metric sorts many more buckets in memory.