What Is a Significant Terms Aggregation in Elasticsearch?

What Is a Significant Terms Aggregation in Elasticsearch?

A complete, plain-English guide to the aggregation that finds what is unusual, not what is popular: how it compares a chosen group of documents with the rest of your data, how its scores are calculated, and how to use it for root-cause hunting, recommendations, and keyword discovery without being fooled by chance.

A doctor is investigating a food poisoning outbreak at a wedding. She asks the guests who fell ill what they ate. Ninety percent of them ate bread. Is bread the culprit? Not necessarily, because ninety percent of all the guests, sick or well, ate bread. Bread is popular, but it does not explain the illness. Then she notices that sixty percent of the sick guests ate the potato salad, while only five percent of the healthy guests did. That is a startling difference, and the potato salad is now the prime suspect.

The doctor did something clever: she did not look for the most common food among the sick. She looked for the food that was unusually common among the sick, compared with everyone else. A significant terms aggregation does exactly this on your data. You choose a group of documents, for example the failed requests of the last hour, or the tickets that mention “refund.” The aggregation compares the terms in that group with the terms across the whole index, and returns the ones that stand out. This guide starts from zero, explains how the comparison works, opens the machinery step by step, and ends with the numbers, the traps, and the habits that turn a clever trick into a trustworthy tool.

1What a Significant Terms Aggregation Actually Is

Three plain ideas, put together: a group, a comparison, and surprise. Once each is clear, the rest follows naturally.

An aggregation in Elasticsearch is a way of summarizing data instead of listing it. Rather than returning the documents that match a query, an aggregation returns counts, averages, groups, and other summaries of them. A bucket aggregation sorts documents into groups called buckets, and reports something about each bucket. The familiar terms aggregation, for example, produces one bucket for each distinct value of a field, and counts the documents in each. It answers the question “what are the most common values?”

The significant terms aggregation is a bucket aggregation that answers a different question: “which values are unusually common in this group of documents?” It works with two sets. The foreground set is the group you are interested in, usually the documents that match your query. The background set is the reference population, by default all the documents of the index. For each term, the aggregation measures how often it appears in the foreground and how often in the background. Terms that appear far more often in the foreground than the background are called significant, and they are returned, ranked by a score.

This is a shift from “popular” to “distinctive.” A term can be extremely popular in the foreground and still not be significant, because it is equally popular everywhere. Words like “the” and “and” are in nearly every document, so they are never distinctive. A term that appears in a modest share of the foreground, but hardly anywhere else, can be highly significant. The aggregation is a tool for finding the fingerprints of a group.

Everyday Analogy

Imagine a crowd at a football stadium. If you ask what people in the crowd are wearing, the most common answer is “shoes,” which tells you nothing, since everyone in the world wears shoes. The distinctive answer is “the red scarf,” because scarves of that color are rare in the general population and very common in this crowd. A significant terms aggregation finds the red scarves of your data.

Foreground
the group of documents you care about, chosen by your query
Background
the reference population, by default the whole index
Surprise
terms are ranked by how unusual they are, not how frequent
The terms aggregation tells you what is common. The significant terms aggregation tells you what is different.

What it is not

A significant terms aggregation is not a full-text search. It does not find documents. It reads the documents that your query has already found and summarizes the terms in a chosen field. It is not a proof of cause: a term being unusually common in a group shows a statistical link, not a reason. And it is not the same as a relevance score, although both compare frequencies. Relevance ranks documents for a query. Significance ranks terms for a group of documents.

i
Do Not Mix Up the Names

Elasticsearch has several similar-sounding aggregations. The terms aggregation counts the most common values. The rare terms aggregation lists the least common values. The significant terms aggregation finds the values that are unusually common in a group. The significant text aggregation does the same job for analyzed text. This guide covers the significant pair, and mentions the others only to draw the contrast.

The one-sentence version

If you remember one line from this chapter, make it this: a significant terms aggregation compares the terms in a foreground group of documents with a background population, and returns the terms that are unusually frequent in the group, ranked by a statistical score.

2Why It Exists: Popular Is Not the Same as Interesting

Every feature answers a frustration. Here the frustration is that counting the most common things nearly always tells you what you already know.

Suppose your support team has a thousand tickets that mention “checkout failing.” An analyst wants to know what these tickets have in common. She runs a terms aggregation on the “product” field. The result: the most common product is the main web store, with 900 tickets. That is true, and useless, because the main web store also accounts for 85 percent of all tickets in the whole system. The count reflects the size of the store, not anything about checkout failures.

What she really wants is the product, browser, region, or error code that is over-represented among the failing tickets. It might be a payment provider that accounts for 45 percent of the failing tickets but only 2 percent of all tickets. That single fact, invisible in a plain count, is probably the cause of the problem. Finding such needles by comparing many fields by hand, and computing percentages in a spreadsheet, is slow and error-prone. The significant terms aggregation does the comparison for every term in a field, at once, inside the search engine.

Everyday Analogy

A newspaper editor wants to know what is special about the readers of the sports section. Saying “most of them read the weather” is true and pointless, because most readers of every section read the weather. Saying “they are seven times more likely than average to read the cycling column” is a real insight. Significance is the difference between the two kinds of statement.

A short history

1

Counting only

Early aggregations counted values and computed metrics. Finding what stood out meant exporting data and analyzing it elsewhere.

2

The significant terms aggregation arrives

In the 1.x era, Elasticsearch added an aggregation that compares a foreground with a background, ranking terms by a statistical score.

3

More scoring heuristics

Alongside the original score, options such as chi-square, mutual information, and others were added, so that users could pick the statistic that suits their data.

4

Significant text and sampling

A version for free text was added that analyzes text on the fly, together with sampling aggregations that limit the work and reduce noise.

5

Related tools

Later releases added a random sampler and text categorization, and Elastic’s user interfaces built explanations of spikes in log rates on similar ideas.

The exact release for each step is worth double-checking in the release notes of your version. The direction of travel is what matters: from “count everything” to “find what is different,” with better statistics and cheaper ways to run it.

Problems it solves

Diagnosis

Root-cause hunting

Which host, version, or region is over-represented among failed requests?

Discovery

Keyword and topic finding

Which words characterize the articles that mention a subject?

Suggestion

Recommendations

Which items are unusually popular among people who liked a given item?

Risk

Fraud and abuse leads

Which merchants, devices, or addresses are over-represented among chargebacks?

Search

Query expansion

Which related terms appear unusually often in documents that match a query?

Analysis

Group profiling

What characterizes a group of customers, patients, or events compared with everyone else?

Why not just use a terms aggregation and compare by hand?

You can, and for one or two candidate values it is fine. But when a field has thousands of distinct values, comparing each one’s share in the group and in the whole index is laborious. The significant terms aggregation does the arithmetic for every value, and ranks them, so that the interesting ones rise to the top. It also uses statistics that guard against being fooled by very rare values that happen to be concentrated in a small group.

3Core Concepts You Need First

A dozen words explain nearly everything about this aggregation. Learn them here, and later chapters will read like common sense.

Sets

Foreground set

The documents you are studying: those that match your query, or belong to a parent bucket.

Sets

Background set

The reference population against which the foreground is compared. By default, all documents of the index.

Counts

Foreground count of a term

How many foreground documents contain the term. Reported as the bucket’s document count.

Counts

Background count of a term

How many background documents contain the term. Reported in the bucket as the background count.

Ratio

Percentage in each set

The count divided by the size of its set. Comparing the two percentages is the heart of the method.

Score

Significance score

A number that says how surprising a term’s frequency is. Higher means more significant.

Score

Heuristic

The formula that turns the four counts into a score. Several are available, with different tastes.

Control

Minimum document count

A floor on how many documents a term must appear in, to keep rare noise out.

Control

Shard size

How many candidate terms each shard sends to the coordinating node before the final ranking.

Field

Keyword field

A field of whole values, such as codes, names, or tags. The natural home of this aggregation.

Field

Text field

A field of analyzed words. It needs the significant text variant, not the plain one.

Helper

Sampler

An aggregation that limits the foreground to the best-matching documents, which cuts cost and noise.

The four numbers behind every term

For each term, the aggregation needs exactly four numbers. The foreground count is how many foreground documents contain the term. The foreground size is how many documents the foreground has. The background count is how many background documents contain the term. The background size is how many documents the background has. Every heuristic is a formula on these four numbers. Nothing else about the documents matters. Grasp this, and the mathematics becomes simple.

Everyday Analogy

Think of a jar of marbles, some red. You draw a handful and find that half are red. Is this handful unusual? It depends on how many marbles in the whole jar are red. If ten percent of the jar is red, a handful with half red is surprising. If half of the jar is red, it is not. The four numbers are the handful’s size and red count, and the jar’s size and red count.

Frequency of a term versus frequency of documents

A subtle but important point: the counts here are counts of documents that contain the term, not the total number of times the term occurs. If a word appears ten times in one document, it still adds one to the count. This matches how Lucene stores information, since the number of documents that contain a term is stored with each term in the index, as the document frequency, and can be read without touching the documents.

Why the background matters most

Change the background and the answer changes. If the background is the whole index, a term such as “checkout” may look unusual for tickets about payment. If the background is only the tickets about billing in general, “checkout” may be entirely ordinary. Choosing the background is the most important decision you make with this aggregation, and Chapter 7 is devoted to it.

!
Common Trap

The bucket’s document count is the count in the foreground, not in the whole index. The whole-index count is the separate background count. Reading the wrong one, and thinking that a term appears in only a few hundred documents overall, is a very common misreading of the response.

Quick glossary

WordPlain meaning
AggregationA summary computed over the documents that a search matches.
BucketOne group in an aggregation’s result, such as one term with its counts.
CardinalityThe number of distinct values in a field.
Document frequencyThe number of documents that contain a term, stored with the term in the index.
Statistical significanceA measure of how unlikely a pattern is to have arisen by chance.
CorrelationTwo things tending to occur together, which does not prove that one causes the other.
ShardA slice of an index. Each shard computes its part of the aggregation.
Circuit breakerA safety limit that stops a request from using too much memory.

4Architecture and Components

Where does the work happen, and which parts of the cluster take part when a significant terms aggregation runs?

A significant terms aggregation is part of a search request. The request carries a query, which defines the foreground, and an aggregation, which describes what to compute. The request goes to every shard involved. Each shard computes its local view of the answer, using only the documents it holds. The coordinating node then combines the shards’ partial answers into the final list.

flowchart TB
    Req["Search with a query and a significant terms aggregation"] --> Coord["Coordinating node"]
    Coord --> S1["Shard 1: local foreground and background counts, top candidate terms"]
    Coord --> S2["Shard 2: local foreground and background counts, top candidate terms"]
    S1 --> M["Coordinating node adds the counts per term and rescores"]
    S2 --> M
    M --> R["Top significant terms returned"]
    
Figure 1: Each shard proposes candidate terms with its local counts. The coordinating node adds the counts across shards and computes the final scores.

Read the picture from top to bottom. The coordinating node forwards the request to a copy of every shard. Each shard finds the documents matching the query, counts the terms among them, looks up the background statistics for its own documents, scores the terms, and sends back its best candidates. The coordinating node adds up the foreground and background counts of each term across shards, computes the score again on the totals, and returns the best ones.

The main components

Input

The query

Defines the foreground: which documents form the group under study.

Input

The aggregation definition

Names the field, the number of terms wanted, the heuristic, and controls such as minimum counts.

Shard work

Aggregator on each shard

Counts terms among the shard’s matching documents and gathers background counts.

Statistics

Term dictionary and postings statistics

Supply the document frequency of each term, which is the background count, without reading documents.

Scoring

The significance heuristic

The formula that turns the four counts into a score for each candidate.

Merge

Reduce step on the coordinating node

Adds up counts from shards, rescores, and keeps the top terms.

Guard

Circuit breakers

Memory limits that protect nodes from aggregations that grow too big.

Optional

Sampler and filters

Limit the foreground or the background to control cost and quality.

Why the shards cannot simply send everything

A field can have millions of distinct terms. If each shard sent all of them, the network and the coordinating node would drown. So each shard sends only its top candidates, a number controlled by the shard size setting. This is efficient, but it makes the answer approximate. A term that scores modestly on every shard, but very well when the counts are added, might not be among any single shard’s top candidates and could be missed. Later chapters explain how to reduce this risk.

Everyday Analogy

A national talent contest has regional rounds. Each region sends its top ten acts to the final. An act that placed eleventh in every region, but would have ranked high nationally, never reaches the final. Sending a few more acts from each region reduces the chance of missing such a talent.

Walking one aggregation through the machine

1

The request arrives

For example: among tickets that mention “checkout failing,” which values of the error code are significant?

2

Each shard finds its foreground

The shard runs the query and collects the matching documents.

3

Terms are counted in the foreground

For each matching document, the shard reads the value of the error code field and counts it.

4

Background counts are looked up

For each candidate term, the shard reads its document frequency from the index statistics.

5

Terms are scored and pruned

The heuristic scores every candidate, and the shard keeps only its best few.

6

The coordinating node merges

It adds the counts across shards, recomputes scores on the totals, and returns the top terms.

i
Why This Matters for Tuning

The cost of the aggregation depends on the size of the foreground, the number of distinct terms in the field, and the number of candidates each shard keeps. The chapters on sampling and performance return to these levers.

5Anatomy of a Request and Its Response

Now we open the request and the response and look at each part. A handful of settings control almost everything.

A significant terms aggregation is defined inside the aggregations section of a search request. You give it a name, name the field to analyze, and optionally set the controls below. The query of the request defines the foreground, and the aggregation reads that foreground. It is common to ask for zero ordinary hits, since the aggregation is the point of the request.

SettingWhat it doesTypical guidance
FieldWhich field’s values are comparedA keyword field, a numeric field, or a text field in the significant text variant
SizeHow many significant terms to returnTen to fifty is usual, since only the top few matter
Shard sizeHow many candidates each shard sendsLarger than size, to reduce missed terms, at a cost
Minimum document countTerms must appear in at least this many foreground documentsKeep it above a handful, to avoid noise from rare terms
HeuristicWhich formula scores the termsThe default first, then compare others
Background filterRestricts the background to a subsetUse it to compare with a more relevant population
Include and excludeAllow or forbid certain terms by pattern or listRemove known boilerplate or irrelevant values
Execution hintHow counting is carried out internallyUsually left to the default
Everyday Analogy

Setting up the doctor’s investigation, you decide which question to ask each guest (the field), how many suspect foods to list (size), how many suspects each table should nominate (shard size), and that a food eaten by only one guest is not worth chasing (minimum document count). You can also decide who counts as the comparison group (background filter).

The shape of the response

The response begins with two numbers about the sets. The first is the number of documents in the foreground. The second is the number of documents in the background. Then comes the list of buckets, one for each significant term. Each bucket contains four things.

Field 1

Key

The term itself, such as a product name, an error code, or a word.

Field 2

Document count

How many foreground documents contain the term.

Field 3

Background count

How many documents in the background contain the term.

Field 4

Score

The significance score under the chosen heuristic. Higher is more significant.

Reading a result by hand

Suppose the response says that the foreground has 2,000 documents and the background has 10 million. A bucket says: key “payment-gateway-x,” document count 900, background count 200,000, score 9.7. You can read this in plain words: the term appears in 900 of the 2,000 foreground documents, which is 45 percent, and in 200,000 of the 10 million background documents, which is 2 percent. The term is about 22 times as frequent in the group as in the whole index. That is a strong signal. The score condenses this ratio and the absolute difference into one number.

The order of results

Buckets are returned in order of decreasing score. This is different from the ordinary terms aggregation, which orders by count. A term with a small document count can top the list, if its background count is tiny. This is exactly the point, but it also explains why the minimum document count matters: without a floor, terms that appear in two foreground documents and nowhere else could dominate the list with impressive-looking ratios that mean nothing.

Nesting inside other aggregations

A significant terms aggregation can be placed inside another bucket aggregation, so that the foreground is the documents of each parent bucket. For example, group tickets by month, and within each month find the significant error codes. Then the foreground of each nested aggregation is that month’s tickets, while the background stays the whole index, unless you say otherwise. This is a powerful pattern, discussed in Chapter 11.

Ask for hits or not

Most requests of this kind ask for no ordinary search hits, only the aggregation. The query still defines the foreground, but the hits list is set to size zero, saving time and bandwidth. When results are needed as well, keep in mind that the aggregation still summarizes all matching documents, not only the returned page.

1

Write the query that defines the group

The foreground is the set of documents it matches.

2

Pick the field to compare

Choose values that could plausibly explain the group.

3

Decide on the background

The whole index, or a relevant subset.

4

Set size, shard size, and the minimum count

Balance thoroughness and noise.

5

Run it and read percentages

Convert counts to percentages in your head, and check that the story makes sense.

!
A Note on Details

Names of options, defaults, and the set of available heuristics differ between versions. This guide describes the ideas, which are stable, and names details only in general terms. Confirm the exact options and defaults in the documentation of the version you run.

6How Scores Are Computed: The Heuristics

The score is a short formula on four numbers. Once you see the formula, the results stop being mysterious.

The default: a balance of two ideas

The default heuristic looks at two things at once. The first is the absolute difference between how common the term is in the foreground and how common it is in the background, measured as percentages. The second is the relative difference: how many times more common it is. The score is the product of the two. A term needs both a large enough difference and a large enough ratio to score well. It scores zero if the term is not more common in the foreground than in the background.

Everyday Analogy

A town’s mayor wants to know which street has an unusual number of stray cats. A street with two cats where the town average is one in ten streets is ten times more than average, but only two cats, so it is not worth a special program. A street with a hundred cats where the average is five has both a huge ratio and a huge absolute count. The default score rewards streets like the second.

A numbers walkthrough

Let us use invented numbers. The background has 10 million documents. The foreground has 2,000, and they are the tickets that mention “checkout failing.” We examine three terms and one suspicious rare term.

TermForeground countForeground percentBackground countBackground percentDefault score
payment-gateway-x90045%200,0002%About 9.7
checkout1,90095%3,000,00030%About 2.1
us-east1,00050%4,000,00040%About 0.13
abc123, a rare code30.15%30.00003%About 7.5

For the first term, the absolute difference is 45 minus 2, or 43 percentage points, and the ratio is 22.5, so the product is about 9.7. For “checkout,” the difference is 65 points and the ratio is about 3.2, giving about 2.1. It is very common in the foreground, but also common in the whole index, so it scores modestly. For “us-east,” the difference is 10 points and the ratio is 1.25, giving about 0.13, which is barely interesting. The rare code has a tiny absolute difference but an enormous ratio, and comes out at about 7.5. It appears in three foreground documents and three background documents in total, so all of its occurrences are in the foreground. This may be a real signal, or pure chance. That is why the minimum document count exists: raise it to ten, and this term is dropped, while the gateway remains.

The available heuristics

HeuristicIdea in plain wordsStrengthWeakness
Default, balancing absolute and relative changeMultiplies the percentage-point gap by the ratioA sensible general default, good at surfacing meaningful termsCan still favor very rare terms without a minimum count
Mutual informationMeasures how much knowing that a document is in the foreground tells you about whether it has the termSolid statistical footing, can also report terms unusually rare in the foregroundPrefers frequent terms, needs care with the background definition
Chi-squareTests whether the term and the group are independent, using a table of four countsFamiliar test, symmetricalBehaves poorly with very small counts
Normalized distanceA distance measure adapted from how often two things occur togetherSimple and often effectiveLess familiar, less tested on some data
PercentageThe foreground count divided by the background countVery simple to explainHighly favors rare terms, gives noise the top places
Custom scriptYour own formula using the four numbersFull controlSlower, and you own the statistical judgment
flowchart TD
    A["Choose a heuristic"] --> B{"Need a safe default?"}
    B -- Yes --> C["Default: balances absolute and relative change"]
    B -- No --> D{"Want a stronger statistical footing?"}
    D -- Yes --> E["Chi-square or mutual information"]
    D -- No --> F{"Want a simple ratio and accept noise on rare terms?"}
    F -- Yes --> G["Percentage"]
    F -- No --> H["Normalized distance or a custom script"]
    
Figure 2: A simple way to choose a scoring heuristic.

Two options that change how heuristics behave

Option

Include negatives

For some heuristics, terms that are unusually rare in the foreground can also be reported. This answers “what is missing from this group?” as well as “what is over-represented?”

Option

Background is a superset

Tells the statistics whether the foreground is entirely contained in the background. It is true by default. If you narrow the background so that it excludes some foreground documents, set it to false.

Scores are for ranking, not for meaning

A score of 9.7 does not mean “97 percent sure.” The scale of scores depends on the heuristic, the size of the foreground, and the size of the background. Scores are good for ordering terms within one result, and for a rough sense of how far the top is from the rest. They are not comparable across different queries, different heuristics, or different indexes. Do not set a fixed threshold on a score and expect it to mean the same thing next month.

Trying several heuristics

1

Start with the default

It is a good general choice, and gives a baseline list.

2

Run one or two others on the same query

Compare the top terms. Stable terms that appear in every list are the most trustworthy.

3

Inspect terms that appear in only one list

They are often rare-term artifacts, or sensitivity to a particular formula.

4

Raise the minimum count and repeat

See which terms survive. Survivors deserve investigation.

!
Rare Terms Are the Usual Trap

Almost every heuristic can be tempted by very rare terms, because their ratios are huge. The best defense is a sensible minimum document count, and a habit of asking “how many documents is this really based on?” before believing any single term.

7Foreground and Background: Choosing What to Compare

The result of the aggregation depends on two choices: who is in the group, and who is in the comparison population. The second is easy to overlook.

flowchart LR
    A["Whole index: the background set"] --> B["The query selects the foreground set"]
    B --> C["Count each term in the foreground"]
    A --> D["Count each term in the background"]
    C --> E["Compare percentages with a heuristic"]
    D --> E
    E --> F["Rank terms by significance, not by popularity"]
    
Figure 3: The foreground comes from the query, the background from the index, and the heuristic compares them.

The foreground: the question you ask

The foreground is whatever your query matches, or, inside another aggregation, the documents of the parent bucket. It is the group whose character you want to understand. A tight, coherent foreground gives clear answers: “tickets mentioning checkout failing,” “requests with status 500,” “customers who cancelled in March.” A loose, mixed foreground gives muddy answers, because its terms reflect many different stories at once.

The default background

By default, the background is all the documents in the indexes that the request searches, taken from the statistics that each index keeps for each term. It does not depend on the query at all. This makes it fast, because these counts are already stored in the index. It also means that the background contains the foreground: every foreground document is also part of the whole index. That is the situation that the default settings assume.

Setting a custom background

Sometimes the whole index is the wrong comparison. If the index contains tickets from ten products, and you study tickets about one product’s checkout, the terms that distinguish that product from the other nine will dominate the results, and they will hide what distinguishes checkout problems from other problems of that product. A background filter lets you restrict the comparison population: for example, only tickets of that product. Then the question becomes “what is unusual about checkout problems, compared with other tickets of this product?”

Everyday Analogy

Suppose you want to know what is special about the runners of a marathon club. Compared with the general public, the answer is “they wear running shoes and are fit.” Compared with other athletes at a sports festival, the answer is different: “they are older and run longer distances.” The comparison group, not the club, decides what stands out.

Useful comparisons

QuestionForegroundBackground
What is unusual about failed requests?Requests with an error statusAll requests
What changed in the last hour?Documents of the last hourDocuments of the previous week
What characterizes one customer segment?Customers in the segmentAll customers
What is special about one product’s complaints?Complaints about the productComplaints about all products, or about similar products
What distinguishes articles about a topic?Articles matching the topic queryAll articles, or articles in the same section
What do fans of one item also like?Items liked by people who like itItems liked by all people

When the background does not contain the foreground

If you set a background filter that excludes some of the foreground documents, for example, a foreground of the last hour and a background of the previous week, then the assumption that the foreground is contained in the background no longer holds. The statistics behave differently. Several heuristics have an option that tells them so, and it must be set correctly, or the scores will be distorted. Read the documentation for your chosen heuristic before using a background that only partly overlaps.

The cost of a custom background

The default background counts are cheap, because they are read from term statistics. A background filter is not stored anywhere in the index. To count a term in the filtered background, Elasticsearch must run the filter together with a term query, for each candidate term. If there are many candidates, this is many extra queries. It works, and is often worth it, but it makes the aggregation slower, sometimes much slower. Keep the filter simple, keep the candidate list modest, and measure.

Subtleties of the default background

Time

Long histories dilute

If the index holds years of data, the background is dominated by old data. A term that is common now but was rare in the past looks very significant.

Deleted

Deleted documents may count

The stored term statistics can include documents that were deleted but not yet merged away, so the background may be slightly overstated.

Indexes

Every searched index counts

When a request searches several indexes or a whole data stream, the background covers all of them. Narrow the search to compare within a relevant set.

Shards

Statistics are per shard

Each shard uses its own background numbers to pick candidates, and the totals are added at the end.

i
Ask Which Story You Are Telling

Before running the aggregation, finish the sentence “this group is unusual compared with …” The blank is your background. If you cannot fill it in, you are not ready to interpret the result.

8Internal Working: What a Shard Does

Now we open the box on a single shard. The work splits neatly in two: counting the foreground, and looking up the background.

flowchart TD
    A["Documents matching the query on this shard"] --> B["Read the field values of each matching document"]
    B --> C["Count each term in the foreground"]
    C --> D["For each candidate term, look up its document frequency in the index: the background count"]
    D --> E["Score with the chosen heuristic"]
    E --> F["Keep the best shard-size candidates"]
    
Figure 4: A shard counts terms in its foreground, reads background counts from index statistics, scores, and prunes.

Counting the foreground

As the search collects matching documents, the aggregator reads, for each one, the value or values of the chosen field. For keyword fields, this uses a compact per-field structure that maps each document to a small number standing for its term, and the aggregator increments a counter for that number. Counting in numbers is much faster than comparing text. At the end of the collection, the counters hold, for each term, how many matching documents contained it. A document with a repeated value still counts once for that term.

Everyday Analogy

A pollster stands at a door and puts a tick on a sheet for each answer she hears, using a short code for each possible answer. At the end of the day she reads the tick counts. She does not keep the full text of each answer, only the counts.

Looking up the background

The background count of a term is just the number of documents in the shard that contain it. That number is the length of the term’s postings list, and it is stored with the term in the term dictionary, as its document frequency. The aggregator reads it directly, without touching a single document. This is why the default background is fast: the index has already done the counting, when it was built. The size of the background is the number of documents in the shard.

Choosing candidates

The shard cannot score every term of a huge field cheaply, and cannot send every term to the coordinating node. It scores its terms, keeps the best in a small priority structure, and sends only those. The number kept is the shard size. Terms that fail the shard-level minimum are dropped early. This step is where the approximation enters, because the shard scores using only its own counts.

Merging on the coordinating node

The coordinating node receives, from each shard, a list of candidate terms with foreground counts, background counts, and the sizes of the sets. For each term, it adds up the counts across shards, adds up the set sizes, and computes the score again on the totals. Then it sorts by score, applies the minimum document count, and returns the top terms. A term that some shards did not send is treated as not seen there, so its total may be a little lower than the true value.

1

Collect

The shard runs the query and feeds each matching document to the aggregator.

2

Count

Counters are incremented for the terms of each document.

3

Look up statistics

For candidate terms, background counts are read from the term dictionary.

4

Score and prune

The heuristic runs, and only the best candidates are kept.

5

Send and reduce

Candidates travel to the coordinating node, which adds counts and rescores.

6

Return

The top terms with their counts and scores are placed in the response.

Two ways to count

Mode 1

Counting by ordinal numbers

The default for keyword fields. Fast, using an array of counters indexed by term number. Memory grows with the number of distinct terms in the field, not with the number of documents.

Mode 2

Counting in a hash map

Counts terms as text in a map. Better when the foreground is small compared with the number of distinct terms, since it only stores the terms actually seen. Selected by a hint.

Memory: where the aggregation can hurt

Aggregations use memory in proportion to the number of distinct terms they must track. For a field with millions of distinct values, and a large foreground, the counters can be big. Elasticsearch protects itself with circuit breakers, which stop a request that would use too much memory, and with a limit on the number of buckets that a request may create. If you hit these limits, the fix is not to raise them, but to reduce the foreground, choose a lower-cardinality field, use sampling, or exclude noise.

Why the postings connection matters

This aggregation is a nice example of the value of the inverted index. The background count of a term is the length of its postings list, which the index computed once, when documents were indexed. The aggregation gets the background nearly free. It is also why the default background always reflects the whole index and never the query, because the index knows nothing about your query when it stores document frequencies.

i
Cheap Background, Costly Filters

Remember the asymmetry: the default background costs almost nothing, because it is precomputed. A background filter costs a query per candidate term, because it is not. Use the filter when the comparison needs it, but never by habit.

9Fields and Types: Keywords, Numbers, and Free Text

The aggregation works on terms, so the kind of field decides what a term is. This choice determines whether the results are useful.

Field typeWhat a term isSuitabilityNotes
KeywordThe whole value, such as a code, a name, or a tagExcellentThe natural home of the aggregation
Numeric, such as identifiersThe number itself, treated as a termGood for categorical numbersNot for measurements, which have too many distinct values
Text, with fielddataEach analyzed wordPoorLoads all words into memory, which is heavy, and is discouraged
Text, with the significant text aggregationEach analyzed word, computed on the flyGoodNo fielddata needed, best used with sampling
Multi-valued keyword fieldsEach value, counted once per documentExcellentIdeal for tags, categories, and lists of items

Keyword fields: the easy case

For fields such as product, region, error code, browser, tag, or user identifier, each value is a term, and the aggregation works directly. If a document has several values in the same field, such as a list of tags, each value is a term for that document. This is how “people who liked this item also liked” recommendations are built: each user is a document with a list of liked items in one keyword field.

Text fields: the harder case

A text field is analyzed: split into words, lowercased, and perhaps stemmed. The inverted index of a text field contains the words. The plain significant terms aggregation would need to read those words back per document, which is not available cheaply, since the index goes from words to documents, and not from documents to words. The original way is to enable a memory structure called fielddata on the field, which loads every word of every document into memory. This is very costly on large fields, and is discouraged.

The significant text aggregation

The significant text aggregation solves this. Instead of using fielddata, it takes the matching documents, reads their original text, analyzes it again on the fly with the field’s analyzer, and counts the words. The background counts still come from the inverted index, since the words were indexed with the same analyzer. No extra memory structure is needed. The price is that it does analysis work at query time, in proportion to the amount of text in the foreground, so it is best used with a limited sample.

flowchart LR
    Q["Query finds the matching documents"] --> S["Sampler keeps the best-scoring documents per shard"]
    S --> A["Analyze the text of each sampled document"]
    A --> F["Filter duplicate text"]
    F --> C["Count the words in the sample"]
    C --> H["Compare with background statistics from the index"]
    H --> R["Significant words"]
    
Figure 5: The significant text aggregation analyzes a sample of documents and compares their words with the background.
Everyday Analogy

A librarian wants to know which words characterize the books about sailing. She could keep an index card for every word of every book, which is enormous. Or she can take a sample of sailing books off the shelf, read them quickly, and tally the words, then compare each word’s frequency with the library’s general word counts, which she already has in the catalog. The second way is cheaper, and good enough.

Details that matter for free text

Duplicates

Filter duplicate text

Repeated passages, such as forwarded messages, quoted replies, and boilerplate, can produce fake significance. An option removes duplicated sequences from each document before counting.

Source

Where the text is read from

By default from the stored source of the document. An option lets you name which source fields to use.

Stop words

Common words fall away naturally

Words like “the” are equally common in the background, so they score near zero without special handling.

Analyzer

Same analysis as indexing

Counts are meaningful only because the same analyzer produced the background statistics.

Stems

Words appear as their analyzed form

If stemming is used, results may be root forms, not the original words.

Cost

Grows with the amount of text

Long documents and large foregrounds make it expensive. Sample.

Choosing the field

1

Ask what could explain the group

Pick fields whose values could plausibly be causes or characteristics: host, version, region, category, tag.

2

Prefer categorical fields

Fields with a moderate number of repeated values give stable statistics.

3

Avoid unique identifiers as the field

A field where nearly every value is unique gives huge lists and no statistics.

4

Use the text variant only for real text

Free text gets the significant text aggregation, ideally with a sample.

5

Run one field at a time, or in parallel

Several significant terms aggregations can run in the same request over different fields.

!
Do Not Enable Fielddata Casually

Turning on fielddata for a large text field to make the plain aggregation work can consume enormous heap and trigger circuit breakers. Use the significant text aggregation instead, or add a keyword field for the values you want to analyze.

10Sampling: Cheaper and Cleaner Results

Analyzing millions of documents is slow, and analyzing weakly related ones is noisy. Sampling helps with both.

Why sample

A query on a big index may match millions of documents, many only loosely related to what you asked. The aggregation would count terms in all of them, spending time and memory, and diluting the signal with the weak matches. A sampler keeps only a limited number of the best-matching documents on each shard, and runs the significant terms aggregation over those. The result is faster, and often clearer, since the sample is the core of the foreground, not its fringe.

Everyday Analogy

A market researcher who wants to understand fans of a band does not interview every person who ever heard a song. She interviews the people who bought tickets. The smaller group is easier to study and more characteristic of the fans.

The kinds of sampler

KindHow it picks documentsBest forWatch out for
SamplerKeeps the top-scoring documents on each shard, by the query’s relevance scoreText queries where relevance ranks documents meaningfullyWith filter-only queries, all scores are equal and the choice is arbitrary
Diversified samplerLike the sampler, but limits how many documents may share one value of a chosen fieldPreventing one author, source, or host from dominating the sampleNeeds a suitable field, and adds a little cost
Random samplerIncludes each document with a chosen probabilitySpeeding up aggregations on very large filtered sets, with uniform coverageResults are approximate, and the sample can miss rare but real terms

A numbers walkthrough

Let us use invented numbers. A query for “outage” matches 4 million documents across 10 shards, taking a large share of the index. Analyzing the text of 4 million documents might take tens of seconds and a lot of memory. A sampler that keeps the top 200 documents on each shard reduces the foreground to 2,000 documents, and the analysis takes a fraction of a second. The terms found are those of the documents that best match the query, so they describe the “core” of outage documents. The background remains the whole index, so the comparison is still against the general population.

Effects of sampling on the answer

Gain

Speed and memory

The work is proportional to the sample, not the whole foreground.

Gain

Less noise from fringe documents

Weakly related documents no longer dilute the terms.

Cost

Smaller foreground, lower counts

With fewer documents, counts are small, and the minimum document count must be lowered accordingly.

Cost

The sample is a choice

What you see reflects the top-ranked documents, not the whole group. A different query wording may change the sample.

Cost

Reproducibility

Random sampling can give slightly different answers on repeated runs unless seeded.

Note

The background is not sampled

Background statistics still come from the whole index.

Diversity: a defense against one loud voice

Imagine a foreground in which a single account posted five thousand nearly identical messages. Without care, its unusual vocabulary would dominate the significant terms, and you would learn about one spammer, not about the topic. A diversified sampler limits the number of documents per account, so that no single source contributes too many. The remaining sample reflects many voices, and the significant terms describe the topic.

When not to sample

  • Small foregrounds. When the foreground has a few thousand documents, sampling loses information without saving much.
  • Counts must be exact. Sampling gives approximate counts, so it is unsuitable when exact percentages are the deliverable.
  • Rare but important terms. A term present in a small share of the foreground might not appear in a small sample.
  • Filter-only foregrounds without a random sampler. The choice among equally scored documents is arbitrary.
1

Try without a sampler first, on a small time window

See whether the result is clear and quick enough.

2

Add a sampler if it is slow or noisy

Start with a few hundred documents per shard.

3

Add diversity if one source dominates

Limit documents per value of a source field.

4

Compare results across sample sizes

Terms that persist as the sample grows are trustworthy.

5

Lower the minimum count to match the sample

A minimum of ten makes sense for a foreground of millions, and not for two thousand.

i
Sampling Is a Dial

Treat the sample size as a dial between speed and fidelity. Turn it down for exploration and dashboards, turn it up for the final analysis whose conclusions you will act on.

11Combining With Other Aggregations

On its own, the aggregation describes one group. Nested inside others, it describes many groups at once, and can show how a story changes across time or place.

Inside a terms aggregation: one story per group

Place a significant terms aggregation inside a terms aggregation, and the foreground of the inner one becomes the documents of each outer bucket. For example, group support tickets by product, and within each product find the significant error codes. You now get one list per product, each showing what stands out for that product compared with the background. This is a compact way to profile many groups at once.

Everyday Analogy

A teacher wants to know what is special about each class in the school. She does not run one survey of the whole school. She runs the same survey in each class, and compares each class’s answers with the school average. The outer grouping is the class, the inner comparison is the significance.

Inside a date histogram: a story over time

Place it inside a date histogram, and you get a list of significant terms for each period. This shows how the character of a group changes: which error codes stand out this week, which topics stand out this month. When a new term suddenly appears in the list, it points to something that began at that time, such as a release or an incident. Because the background is the whole index, long-standing patterns are suppressed, and newly unusual terms rise to the top.

Inside a filters aggregation: comparing named groups

A filters aggregation lets you define several named groups with queries, such as “failed requests,” “slow requests,” and “all requests from mobile.” Placing the significant terms aggregation inside gives one list per named group, from a single request. This is useful for side-by-side comparisons.

Outer aggregationWhat each inner foreground isTypical question
Terms on a categoryThe documents of each categoryWhat is unusual in each product or region?
Date histogramThe documents of each time intervalHow does the unusual vocabulary change over time?
Filters with named queriesThe documents matching each filterWhat distinguishes failures from slow successes?
SamplerThe sampled best-matching documentsWhat characterizes the core of the topic?
Nested or geographic groupingsThe documents of each groupWhat is unusual in each area?

What stays the same: the background

In all these nestings, the background is by default still the whole index, not the parent bucket. So a term that is unusual for a product may simply be unusual because that product differs from the rest, which may or may not be what you want. If you want to compare each group with a narrower population, set a background filter. Be aware that a background filter is applied to the entire aggregation, not automatically per parent bucket.

Adding companions

Companion

Top hits

Show a few example documents for each significant term or group, so that a human can check whether the finding makes sense.

Companion

Cardinality

Count how many distinct users, hosts, or sessions are behind a term, to tell a widespread pattern from a single noisy source.

Companion

Metrics

Average latency or total revenue for documents with the significant term, to measure its impact, not just its frequency.

Companion

Date ranges

When the significant term first and last appeared, to relate it to events.

The cost multiplies

Nesting multiplies work. If the outer aggregation has a hundred buckets and each contains a significant terms aggregation over a field with thousands of candidate terms, the total memory and time grow quickly, and the request may hit the bucket limit or a circuit breaker. Keep outer aggregations small, keep the size of the inner one modest, and restrict the time window. Test on a small range before running on months of data.

1

Start with the inner aggregation alone

Make sure it gives a sensible answer for one group.

2

Wrap it in a small outer aggregation

A handful of groups or periods.

3

Add companions for evidence

Example documents, distinct counts, and metrics.

4

Widen gradually

Increase groups and time range while watching latency and memory.

i
Pair Every Finding With Evidence

A significant term is a lead, not a verdict. Attach a few example documents and a distinct count to each one, so that a person can quickly judge whether it is a real pattern or an accident.

12Use-Case Patterns: Where the Aggregation Shines

The same mechanism supports very different jobs. Each has its own choice of foreground, background, and field.

Pattern 1: root-cause hunting

flowchart LR
    A["Query: failed requests in the last hour"] --> B["Significant terms on host, version, region, and error code"]
    B --> C["Terms over-represented among the failures"]
    C --> D["Investigate: one host, one release, or one region"]
    
Figure 6: Comparing failures with everything else points at the attributes that are unusually common among them.

The foreground is the set of failing requests. The background is all requests. The fields are attributes that might explain the failure: host, software version, region, client type, endpoint. If one host appears in 70 percent of failures and only 5 percent of all requests, it is a strong lead. This is the same idea that some Elastic tools use to explain sudden changes in log rates, by comparing a period of change with a baseline period.

Everyday Analogy

A hospital notices more patients with a stomach illness. Instead of listing what all the patients ate, the team compares their meals with those of healthy visitors, and finds one dish that is far more common among the sick. The comparison points at the source.

Pattern 2: recommendations

flowchart TD
    A["Find users who liked item X"] --> B["Foreground: all items liked by those users"]
    B --> C["Background: all items liked by all users"]
    C --> D["Items unusually popular among the X group"]
    D --> E["Recommend those items"]
    
Figure 7: People who liked one item are compared with everyone, to find items that are unusually popular among them.

Each user is a document with a list of liked items in a keyword field. The foreground is the users who liked item X. The aggregation over the list of liked items finds items that these users like much more than users in general. This avoids the trap of recommending the most popular items overall, which everyone likes and which tell you nothing about the taste of the X group. It is the same idea as the doctor’s potato salad: the recommendation is the item that is distinctive, not merely common.

Pattern 3: fraud and abuse leads

Take confirmed chargebacks as the foreground, and all transactions as the background. Significant merchant identifiers, device types, issuing banks, or shipping countries are candidates for investigation. Because fraud is rare and concentrated, the aggregation is well suited. It generates leads for analysts, not automatic decisions, since legitimate customers may share the same attributes.

Pattern 4: keyword and topic discovery

Use articles that match a subject as the foreground, and all articles as the background. The significant text aggregation returns words that characterize the subject: for “electric vehicles” it might return “charging,” “battery,” and “range,” and not the ubiquitous “car.” These words can label topics, populate tag suggestions, or seed a synonym list.

Pattern 5: query expansion

To help users who search with too few words, run their query, take the significant words from the top documents, and offer them as suggested refinements, or add them quietly to the search with a low weight. This is a classic technique for improving recall, and the aggregation provides it in one request. Keep the added terms modest, and test whether they help on judged queries, because expansion can also drift away from the user’s intent.

Pattern 6: profiling customer groups

The foreground is a group, such as customers who cancelled, or customers who bought a premium plan. The aggregation over plan features, acquisition channel, country, or support topics shows what is over-represented in that group. It summarizes a group without needing a statistician, and prompts hypotheses for further study.

Use caseForegroundBackgroundFieldsMain caution
Root causeFailed requestsAll requestsHost, version, region, endpointCorrelated attributes may point at the same cause
RecommendationsItems liked by fans of XItems liked by all usersItem identifiersSparse data gives noisy suggestions
Fraud leadsConfirmed chargebacksAll transactionsMerchant, device, countryLeads only, not proof, and privacy limits
Topic discoveryArticles about a subjectAll articlesArticle textDuplicates and boilerplate distort
Query expansionTop documents of the queryAll documentsArticle textDrift away from user intent
Customer profilingA defined customer groupAll customersPlan, channel, country, topicsCorrelation is not cause
!
Sensitive Domains Need Extra Care

When the documents describe people, in health, finance, or security, significant terms can surface correlations that are sensitive, misleading, or unfair if acted upon blindly. Use the results to prompt human review, apply privacy thresholds, and never treat a statistical association as a judgment about an individual.

13Interpreting Results Without Being Fooled

The aggregation always returns something. Whether that something is meaningful is your job to judge. Here are the classic ways to be fooled, and the defenses.

Correlation is not causation

A term being unusually common in a group shows that the two go together. It does not show that the term causes the group. A particular server may be over-represented among failures because it serves a busy region, or because it received a new release, or because it is where the failing customers happen to live. The term is a lead, and the causal story must be checked by looking at documents, at timelines, and at experiments.

Everyday Analogy

Ice cream sales and sunburn cases rise together in summer. Ice cream does not cause sunburn. Both follow the sun. A significant term may be a stand-in for a hidden third factor in the same way.

Small numbers

A term that appears in three foreground documents and three background documents in total has a perfect ratio and no evidence. Chance alone can produce such patterns. Always look at the document count, and require a sensible minimum. Treat any finding built on a handful of documents as a curiosity, not a conclusion.

Many terms, many chances

If a field has a hundred thousand distinct values, some of them will look unusual by pure chance, just as some coin flips out of a huge number will look lucky. The more terms examined, the more likely it is that some apparent finding is an accident. Defenses include a higher minimum count, focusing on fields with a moderate number of values, requiring that findings persist across time windows, and confirming with a second, independent sample.

Redundant evidence

Several top terms may describe the same underlying fact. A host name, its IP address, and its rack number are three names for one machine. A product and its version are related. The list of significant terms can therefore look like many findings while containing one. Group related terms, and count the distinct stories, not the distinct terms.

Mixed groups and Simpson’s paradox

When a foreground blends several different populations, the significant terms may describe the mixture, not any single population, and may even point in the wrong direction for each part. Splitting the foreground into meaningful subgroups, with nested aggregations, often reveals that the story is different in each.

Effect size versus significance

A very large foreground can make even tiny differences statistically clear, while being practically meaningless. A term that is 51 percent of the foreground and 50 percent of the background is a real difference in a huge sample, and a useless one. Always read the percentages, not only the score, and ask whether the difference is big enough to matter.

Check 1

Look at the counts

How many documents support the term in the foreground and the background?

Check 2

Convert to percentages

Say aloud: “this term is in X percent of the group and Y percent of everyone.”

Check 3

Read example documents

Open a few. Do they show what the term suggests?

Check 4

Repeat on another window

Does the term persist on different days or another sample?

Check 5

Test the reverse

Filter on the term and see whether the group’s defining property is over-represented.

Check 6

Look for a hidden third factor

Region, time, customer size, or release may explain both.

Validating a finding with a follow-up query

1

State the finding in plain words

“Failures are concentrated on version 4.2.”

2

Measure the failure rate with and without the term

Failures among version 4.2 requests versus failures among all others.

3

Check the timeline

Did failures start when version 4.2 was deployed?

4

Control for other factors

Compare within one region, or one customer size.

5

Test a fix

Roll back or patch, and see whether the effect disappears.

!
Never Present a Score as a Proof

Show people the counts, the percentages, and some example documents. A bare score invites false confidence. A table with “in 45 percent of failures, 2 percent of all requests” invites sensible thinking.

14Performance, Sizing, and Tuning

Significant terms aggregations are more expensive than plain counts. Knowing where the cost comes from tells you how to keep them cheap.

Where the cost comes from

Foreground

Number of matching documents

Each matching document’s field values must be read and counted.

Cardinality

Number of distinct terms

Counters and candidate lists grow with the number of distinct values in the field.

Candidates

Shard size

More candidates per shard mean more scoring, more network, and more merging.

Background

Background filter

A query per candidate term, instead of a cheap statistics lookup.

Text

Analysis at query time

Re-analyzing the text of every foreground document in the text variant.

Nesting

Multiplication by parents

Every outer bucket repeats the whole inner computation.

A numbers walkthrough

Let us use invented numbers. A foreground of 5 million documents is aggregated over a keyword field with 200,000 distinct values, across 10 shards. Each shard sees, on average, 500,000 documents, and counts values in an array of 200,000 counters: about 800 kilobytes per shard for the counters, which is small. The time is dominated by the reading of 500,000 values per shard, which takes tens of milliseconds to a few hundred, depending on caching. Adding a sampler that keeps 500 documents per shard reduces the reading to 5,000 values per shard, a hundredfold saving. Now imagine a background filter: with a shard size of 100, each shard would run 100 extra filtered queries to get background counts, which may take longer than the entire counting. This shows which choices matter most: the size of the foreground, the presence of a background filter, and nesting.

Everyday Analogy

Counting ballots is quick when each ballot is a tick in one column. It becomes slow if, for every candidate, you must also look up their vote share in a separate city archive that is not indexed. The extra lookup is the background filter.

Tuning levers

LeverEffect on qualityEffect on costTrade-off
Narrower query or time windowSharper foregroundFewer documents to readLess data, less stable statistics
Use a samplerCleaner, more focusedLarge savingApproximate counts
Higher minimum document countLess noise from rare termsFewer candidatesMay drop real but rare signals
Smaller shard sizeHigher risk of missed termsLess scoring and networkAccuracy versus cost
Include or exclude listsRemoves known noiseFewer terms to considerMaintenance of the lists
Use a lower-cardinality fieldMore stable statisticsSmaller countersLess specific findings
Avoid a background filter unless neededUses the whole indexUses cheap statisticsComparison may be less apt
Build global ordinals early for hot fieldsNoneRemoves a delay at the first query after refreshExtra work at each refresh
Limit nesting and outer bucket countsNonePrevents multiplicative growthFewer groups per request
Run heavy analyses asynchronouslyNoneAvoids timeoutsResults arrive later

Caching and repeated requests

Aggregation results for requests that return no hits can be remembered in the shard request cache, and served again as long as the shard has not changed. On busy indexes, refreshes invalidate it often, so the benefit is greatest on data that no longer changes, such as older time-based indexes. Dashboards that run the same aggregation repeatedly on frozen periods benefit most. Queries that use the current time, in relative form, change with every request and defeat the cache, unless the time is rounded.

Limits that protect the cluster

  • The bucket limit. A single request may create only a limited number of buckets in total. Deep nesting can reach it.
  • Circuit breakers. A request that would use too much memory is stopped, with an error, before it can harm the node.
  • Timeouts. A search can be given a time limit, after which partial results are returned. For aggregations, partial results may be misleading.
  • Asynchronous search. Long analyses can be submitted, and their results fetched later, so that clients do not hold connections open.
i
Explore Small, Then Scale

Develop the analysis on a narrow time window with a sampler, so that each experiment takes a second. When the analysis is right, widen the window, and lower the sampling only as far as the answer requires.

15Advantages, Disadvantages, and Trade-offs

Every design carries a price. Here is the honest balance sheet of the significant terms aggregation.

Advantages

  • Finds what is distinctive, not just what is popular.
  • Does in one request what would take many queries and a spreadsheet.
  • Background counts come almost free from the index’s statistics.
  • Works on keywords, on categorical numbers, and, with the text variant, on free text.
  • Combines with other aggregations to profile many groups or periods.
  • Several heuristics let you match the statistic to your data.
  • Runs inside the cluster, next to the data.

Disadvantages

  • Shows association, not cause, and is easy to over-interpret.
  • Sensitive to the choice of background and heuristic.
  • Rare terms can produce impressive-looking noise.
  • Results are approximate across shards.
  • More expensive than plain counts, especially with filters, text, or nesting.
  • Scores are not comparable across queries or heuristics.
  • Correlated terms can make one finding look like many.
Trade-offLeaning toward thoroughnessLeaning toward speed and stability
Sample sizeLarge or none: more evidence, slowerSmall sample: fast, coarser
Shard sizeLarge: fewer missed terms, more workSmall: quick, may miss terms
Minimum document countLow: finds rare signals, more noiseHigh: stable, may miss real rare causes
BackgroundCustom filter: apt comparison, costlyWhole index: cheap, less specific
HeuristicStatistical, with careful setup: principled, needs careDefault: reasonable, less transparent
Field choiceHigh-cardinality field: specific, noisy and heavyLow-cardinality field: stable, general
Time windowLong: more data, diluted backgroundShort: focused, small counts
Everyday Analogy

A metal detector set to high sensitivity finds every small coin and every bottle cap. Set to low sensitivity, it finds only large objects and misses small treasures. The right setting depends on what you are hunting, and on how much digging you are willing to do.

How ambitious should you be?

SituationRecommended stance
Exploring an incident quicklySample, default heuristic, short window, generous shard size
A dashboard that refreshes oftenFixed windows, caching, small sizes, low-cardinality fields
A recommendation feature in productionPrecomputed or cached results, strong minimum counts, offline evaluation
An investigation whose findings will be acted uponRepeat with several heuristics and windows, verify with follow-up queries
Analysis involving personal dataHigh minimum counts, access controls, and human review

16Reliability, Consistency, and Reproducibility

A good analysis gives the same answer tomorrow. Here is why a significant terms aggregation might not, and what to do about it.

Approximation across shards

As Chapter 8 explained, each shard proposes only its best candidates, using its local counts. The coordinating node adds up the counts of the candidates it received. A term that no shard proposed is invisible, even if its combined counts would have ranked it high, and a term proposed by some shards but not others has undercounted totals. The result is an approximation. The error is usually small for strong signals, and larger for borderline ones. Raising the shard size reduces the error at some cost, and a small number of shards reduces it too.

Everyday Analogy

Regional election officials report only their top five candidates to the national count. A candidate who placed sixth in every region, but would have won nationally, is never counted. Asking each region to report its top twenty makes a mistake less likely.

Replicas and segments differ

An aggregation runs on one copy of each shard, chosen by the coordinating node. Different copies of the same shard have different segments, and so can have slightly different term statistics, especially the background counts, which may include deleted documents until merges remove them. Two runs of the same request, served by different copies, can return slightly different scores, and, rarely, a different order for borderline terms. Using a stable preference so that the same user is served by the same copies makes repeated analyses more consistent.

Data changes between runs

Indexes are alive. New documents arrive, old ones are updated or deleted, and merges reshape segments. A foreground defined by “the last hour” changes continuously. For a reproducible analysis, fix the window with absolute times, run it on data that has stopped changing, and record the date, the version of Elasticsearch, and the exact request.

Source

Shard-level approximation

Reduce with a larger shard size or fewer shards.

Source

Replica differences

Reduce with a stable search preference.

Source

Live data

Reduce with fixed, absolute time windows on settled data.

Source

Random sampling

Reduce with a fixed seed where available.

Source

Deleted documents in statistics

Reduce by merging, when appropriate, before an important analysis.

Source

Version and settings changes

Record them with each result, so differences can be explained.

Partial failures

If a shard fails or times out during the request, the response may still arrive, reporting that some shards were unsuccessful. The aggregation then covers only the shards that answered, which changes both the foreground and the background. Always check the summary of shard successes and failures in the response, and treat an analysis with failed shards as incomplete. In automated systems, refuse to act on such a result.

1

Check that all shards answered

Read the shard summary. Rerun if any failed.

2

Fix the time window in absolute terms

Do not use “now” for analyses you want to repeat.

3

Use a large enough shard size

Especially for analyses that will drive decisions.

4

Repeat once

Findings that change between two runs are not ready to be trusted.

5

Save the request and the result

Keep both, with the version and the date, as the record of what was found.

Availability of the feature

The aggregation runs on the data nodes and the coordinating node like any search. If nodes fail, replicas take over, and the aggregation continues on them, with possible slight differences. During heavy indexing, or after restarts with cold caches, it may be slower. Plan capacity so that analytical requests do not compete with user-facing search: run them on a schedule, off-peak, or against dedicated resources.

!
Do Not Automate Decisions on One Run

If a system takes action based on significant terms, such as blocking a merchant or rolling back a release, require confirmation from repeated runs, a minimum evidence threshold, and a human check for consequential actions.

17Security and Privacy Considerations

An aggregation returns summaries, not documents. That feels safe, and is not always so.

Aggregations can reveal what documents cannot

A user who is not allowed to read individual documents may still be allowed to run aggregations, on the theory that summaries are harmless. But a significant terms aggregation can reveal a lot. If the foreground is narrow enough, for example the documents about one named person, the returned terms, with their counts, describe that person: their address, employer, or health topics. Summaries over small groups are effectively the data itself.

Everyday Analogy

A published table saying “average salary in the department: 62,000” is harmless when the department has a hundred people. If the department has one person, the table reveals that person’s salary. The size of the group decides whether a summary protects or exposes.

Protecting against small-group disclosure

Rule

Set a meaningful minimum document count

Do not return terms based on only a few documents. A floor of tens, not three, is safer for sensitive data.

Rule

Limit the foreground size

Refuse or blur analyses whose foreground is smaller than a threshold.

Rule

Control who can aggregate

Aggregation rights should be granted as deliberately as search rights, on sensitive indexes.

Rule

Limit the fields

Not every field should be available for aggregation by every user.

Rule

Watch for repeated narrowing

Multiple queries with slightly different filters can isolate an individual. Rate-limit and log.

Rule

Apply role-based restrictions

Use platform features so that users’ analyses cover only what they may see.

Document-level security and statistics

Elasticsearch can restrict each user’s search to the documents they are allowed to see. For this aggregation, an important question is whether the background statistics reflect only the allowed documents, or the whole index. The default background comes from index-wide term statistics, and term statistics are a well-known way in which information about hidden documents can leak: a background count that includes documents the user cannot see reveals how many such documents contain a term. Test how your version and your security configuration behave, with a restricted user, and consider using an explicit background filter that enforces the same restriction, at some cost in speed.

Free text and sensitive words

The significant text aggregation returns words from the documents. If those documents contain personal data, the returned words may include names, addresses, or identifiers. Restrict this feature on sensitive text, use stop lists or exclusion patterns to hide categories of terms, and review the output before it is shown to a wide audience.

Abuse and cost

  • Expensive requests. Deep nesting, high-cardinality fields, and background filters can consume a lot of memory and time. Limit sizes and depths for untrusted users.
  • Denial of service by aggregation. A few heavy requests can slow the cluster for everyone. Use timeouts, quotas, and separate resources for analytics.
  • Exploring the data through summaries. Automated scripts can map the contents of an index with many aggregations. Use rate limits and audit logs.

Audit and accountability

Analytical queries deserve logging, like any access to sensitive data. Record who ran which aggregation, over which data, when, and with what result size. Where your subscription supports audit logging, turn it on for sensitive indexes. When findings are used for decisions about people, keep the evidence and the request that produced them.

i
Do Not Skip the Basics

Turn on authentication and encryption, even for clusters that seem internal, and give analysts only the roles they need. A clever aggregation over an unprotected index is a data leak with extra steps.

18Monitoring, Logging, and Metrics

You need to watch two things: whether the aggregation is healthy for the cluster, and whether its answers are healthy for the people who rely on them.

Windows onto the cost

WindowWhat it showsUse it to
Profile option on a searchTime spent in each aggregation, and how many documents were collectedSee which part of a request is slow
Slow search logsSearches slower than a threshold, with their full definitionFind the heavy aggregations
Node statistics for circuit breakersHow often memory limits stopped a requestSpot aggregations that are too big
Request cache statisticsHow often aggregation results were served from cacheJudge whether caching is helping
Task listingCurrently running searches and how long they have runFind and cancel runaway analyses
Asynchronous search statusProgress and completion of long analysesManage heavy jobs
Heap and garbage collection metricsMemory pressure on data nodesSee the effect of aggregations on the cluster

Metrics to chart

MetricWhat it tells youWarning sign
Latency of aggregation requestsHow long analyses takeRising steadily as data grows
Circuit breaker tripsRequests stopped for memory reasonsAny sustained increase
Bucket limit errorsRequests too wide or too deepRepeated failures from one dashboard or script
Share of requests with failed shardsCompleteness of resultsAny nonzero share in automated jobs
Foreground sizesHow many documents analyses coverVery large, suggesting missing sampling
Share of results emptied by the minimum countWhether the floor is too high or the foreground too smallMany empty results
Stability of top terms between repeated runsReproducibilityLarge overlaps lost between runs
Heap use during analytical hoursImpact on other workloadsSpikes correlated with analysis jobs
flowchart TD
    A["Run the aggregation"] --> B{"Did all shards answer?"}
    B -- No --> R["Rerun, or treat the result as incomplete"]
    B -- Yes --> C["Repeat on another window or another sample"]
    C --> D{"Do the top terms persist?"}
    D -- No --> E["Treat as noise: raise the minimum count or narrow the fields"]
    D -- Yes --> F["Check counts, percentages, and example documents"]
    F --> G["Follow up with targeted queries before acting"]
    
Figure 8: A validation loop that turns a raw result into a trustworthy finding.

Monitoring the quality of the answers

Cluster metrics tell you whether the aggregation is affordable. They do not tell you whether it is right. For analyses that feed decisions or products, add checks on the results themselves. Measure the overlap of the top terms across repeated runs, as a stability score. Track how often the top term changes from day to day. Keep a small set of known cases, such as a past incident with a known cause, and rerun them after upgrades or configuration changes, to confirm that the aggregation still surfaces the known culprit.

Everyday Analogy

A weather forecaster tracks both how long her computer takes to run a model and how often the forecast turned out right. A fast model that is often wrong is no use. A slow model that is always right may still be too slow. Both numbers are needed.

Logging that helps

Request

The full definition

Query, field, heuristic, sizes, sampling, and filters, so that any result can be reproduced.

Context

Time window and index set

Which data the analysis covered, in absolute terms.

Result

Set sizes and top terms

Foreground size, background size, and the top few terms with counts.

Health

Shard summary and timing

How many shards answered, and how long it took.

Who

User and purpose

Who ran the analysis, and why, on sensitive data.

Version

Elasticsearch version

So that differences after upgrades can be explained.

A troubleshooting playbook

1

If the request is slow, profile it

Find out whether the time is in collecting documents, counting, background lookups, or a nested aggregation.

2

If it fails with a memory error, look at cardinality and nesting

Reduce the foreground, sample, choose a lower-cardinality field, or reduce buckets.

3

If results look like noise, raise the minimum count

And check whether the foreground is coherent and the background apt.

4

If results are empty, lower the minimum or widen the foreground

A small foreground rarely reaches high counts.

5

If results change between runs, check shards and windows

Failed shards, moving time windows, and different replicas are the usual causes.

6

If everything is dominated by common terms, revisit the background

Maybe the background is too narrow, or the field contains boilerplate.

i
Alerts Worth Having

Alert on circuit breaker trips, on rising latency of analytical requests, on automated analyses with failed shards, on sudden drops in the stability of top terms, on heap pressure during analysis hours, and on unusually heavy aggregation requests from untrusted users.

19Design Patterns and Anti-patterns

Good habits make significant terms trustworthy and affordable. Bad habits produce confident nonsense.

Patterns that work

1

Write the comparison as a sentence first

“This group is unusual compared with that population.” If you cannot say it, you cannot choose the foreground and background.

2

Sensible floors on evidence

A minimum document count suited to the size of your foreground.

3

Sample, then confirm

Explore quickly with a sample, and confirm the shortlist without one.

4

Pair findings with evidence

Example documents, distinct counts, and percentages beside every term.

5

Compare heuristics and windows

Trust terms that survive changes of method and period.

6

Nest carefully

Small outer aggregations, modest inner sizes, and short windows while developing.

7

Treat results as leads

Follow up with targeted queries and, where possible, experiments.

Everyday Analogy

A careful detective treats every clue as a lead. She checks it against other evidence, asks whether it could be a coincidence, and only then names a suspect. A careless detective arrests the first person who matches a hunch.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
What people do

They use a plain terms aggregation to find “what is special” about a group, and report the most common values.

Why it hurts

The most common values in a group are usually the most common values everywhere. The result shows the size of categories, not their distinctiveness.

Better approach

Use the significant terms aggregation, which compares against a background, when the question is about what stands out.

ANTI-PATTERN 02Avoid
What people do

They accept impressive scores built on a handful of documents, with a minimum count of one or two.

Why it hurts

Very rare terms produce huge ratios by chance. The list fills with accidents that look like discoveries.

Better approach

Set a minimum document count proportional to the size of the foreground, and read the counts beside every score.

ANTI-PATTERN 03Avoid
What people do

They run the aggregation over years of data with the whole index as background, and treat any current spike as a new discovery.

Why it hurts

A long history dilutes the background. Terms that were normal last year but are rare in old data look unusual today.

Better approach

Choose a background that matches the question, such as the previous few weeks, using a background filter.

ANTI-PATTERN 04Avoid
What people do

They enable fielddata on a large text field so that the plain aggregation can be used on words.

Why it hurts

Fielddata loads every word of every document into memory. Nodes run short of heap, and circuit breakers trip.

Better approach

Use the significant text aggregation with a sampler, or create a keyword field for the values you need.

ANTI-PATTERN 05Avoid
What people do

They nest significant terms inside several levels of buckets over long periods, in one request.

Why it hurts

The work multiplies. The request hits the bucket limit or a memory breaker, or slows the cluster for everyone.

Better approach

Keep the outer levels small, restrict the window, sample, and run large analyses asynchronously.

ANTI-PATTERN 06Avoid
What people do

They present scores to decision makers as if they were probabilities or proofs.

Why it hurts

Scores depend on the heuristic and the set sizes. Readers overestimate certainty and act on correlations as if they were causes.

Better approach

Show counts, percentages, and examples, and state clearly that the finding is a lead to be verified.

ANTI-PATTERN 07Avoid
What people do

They run the free-text variant on data full of quoted replies, signatures, and repeated boilerplate.

Why it hurts

Repeated passages inflate the counts of their words, and the “significant” words describe the boilerplate, not the topic.

Better approach

Turn on duplicate filtering, exclude known boilerplate terms, and use a diversified sample.

ANTI-PATTERN 08Avoid
What people do

They allow open aggregation access to sensitive indexes, with tiny minimum counts, because “it is only summaries.”

Why it hurts

Summaries over small groups reveal individuals, and background statistics may include documents the user cannot see.

Better approach

Grant aggregation rights deliberately, require high minimum counts, test with restricted users, and log access.

20Best Practices and Common Mistakes

A short list you could hand to a new teammate on their first day.

Best practices

Question

Define foreground and background in words

Know what you compare with what, before you run anything.

Fields

Choose categorical fields

Moderate cardinality, meaningful values, no unique identifiers.

Evidence

Set a minimum count for the data size

Higher for large foregrounds, and never as low as one or two.

Cost

Sample while exploring

Speed helps thinking. Confirm without sampling.

Trust

Compare heuristics and windows

Stable terms deserve attention, fragile ones do not.

Reading

Read percentages, not only scores

And open example documents.

Care

Protect small groups

Privacy thresholds and access control on sensitive data.

Records

Save requests and results

With time window, version, and shard summary.

Common mistakes

  • Reading the bucket count as the overall count. The bucket’s document count is the foreground count. The overall count is separate.
  • Forgetting that the default background is the whole index. It may contain unrelated data that distorts the comparison.
  • Treating association as cause. The term is a lead, not a verdict.
  • Trusting rare terms. Ratios on tiny counts mean little.
  • Using the plain aggregation on analyzed text. Use the text variant, and sample.
  • Ignoring failed shards. An incomplete run is not a result.
  • Comparing scores across heuristics or queries. They live on different scales.
  • Setting a background filter that excludes foreground documents without telling the heuristic. The statistics are then distorted.
  • Running huge nested analyses interactively. Use asynchronous search, samples, and short windows.

Myths versus facts

MythFact
It returns the most common terms.It returns terms that are unusually common compared with a background.
A high score proves a cause.It shows a statistical association, which needs verification.
The background is the query’s complement.By default it is the whole index, including the foreground.
Scores can be compared across queries.Scores depend on the sets and the heuristic, and are for ranking within one result.
It works well on any text field directly.Analyzed text needs the significant text variant, ideally with sampling.
The result is exact.It is approximate across shards, and sampling adds more approximation.
Aggregations are harmless because they return summaries.Summaries over small groups can reveal individuals.
More terms examined means better findings.More terms means more chance of accidental findings.
!
A Golden Rule

A significant term is a question, not an answer. It tells you where to look. What you find when you look, and what you do about it, must come from the documents, the timeline, and, where possible, an experiment.

21Real-World and Industry Examples

Where does the significant terms aggregation quietly earn its keep?

Many well-known organizations have said publicly that Elasticsearch is part of their systems, including Wikipedia’s search, Netflix, Uber, and Stack Overflow. They rarely publish how they use aggregations like this one, so the scenarios below are typical patterns for such workloads, not descriptions of anyone’s private configuration.

Incident analysis for an online service

A streaming or ride-hailing company sees a jump in failed requests. An engineer compares the failed requests of the last thirty minutes with all requests of the previous day, across fields such as host, software version, region, and mobile app version. One app version accounts for 62 percent of the failures and 4 percent of all traffic. The team confirms with a follow-up query that the failure rate for that version is far higher in every region, and rolls it back.

Product recommendations from behavior

A marketplace of the size of Amazon or eBay stores, for each shopper, a list of purchased item identifiers. To recommend items for a shopper who bought a camera, it takes shoppers who bought that camera as the foreground, and all shoppers as the background. The aggregation over purchased items returns accessories that are unusually popular among these shoppers, such as a particular lens, rather than the best sellers in general.

Security analytics: attributes of an attack

A security team takes the login attempts flagged as credential stuffing as the foreground and all login attempts as the background. Significant user agents, network ranges, and countries reveal the attacker’s tooling. The results become blocking rules for the team to review, with higher minimum counts to avoid blocking legitimate users.

Topic discovery in a news archive

A publisher wants tags for articles about a new topic. It uses the significant text aggregation on articles that match a seed query, with a sampler of the best-matching documents and duplicate filtering to remove syndicated copies. The returned words seed a topic page and a synonym list, reviewed by editors.

Support triage

A software company groups tickets by week, and within each week finds the significant product areas and error phrases. A phrase that suddenly becomes significant points to a new issue, often days before the volume of tickets makes it obvious. The support lead uses it as an early warning, together with example tickets.

Public health surveillance, carefully

An agency compares reports of an illness with all reports, looking for unusually common exposures, locations, or foods. Because these data concern people, the analysis uses high minimum counts, restricted access, and human epidemiologists, who treat the results as hypotheses to investigate with proper studies.

i
The Common Thread

In every example, the winning ideas are the same: a coherent foreground, a background that fits the question, evidence floors, samples for speed, examples beside scores, and follow-up checks before any action is taken.

22Frequently Asked Questions

Short answers to the questions that come up most often.

Q1What is a significant terms aggregation in one sentence?
It is a bucket aggregation that compares the terms in a foreground group of documents with a background population, and returns the terms that are unusually frequent in the group, ranked by a statistical score.
Q2How is it different from a terms aggregation?
A terms aggregation returns the most common values. A significant terms aggregation returns the values that are unusually common in the group compared with a background, which is a different and more informative question.
Q3What are the foreground and the background?
The foreground is the group of documents you study, usually those matching your query. The background is the reference population, by default all documents in the searched indexes.
Q4What does the document count in a bucket mean?
The number of foreground documents that contain the term. The number of background documents that contain it is reported separately as the background count.
Q5How is the score calculated?
By a heuristic that uses four numbers: the term’s count and the set size in the foreground, and in the background. The default balances the absolute and relative difference between the two percentages. Other heuristics use chi-square, mutual information, and more.
Q6Can I compare scores between two requests?
No. Scores depend on the heuristic and the sizes of the sets. Use them to rank terms within one result.
Q7Why do rare terms sometimes top the list?
Their ratios are huge even when the evidence is tiny. Raise the minimum document count, and read the counts beside the scores.
Q8How do I choose the background?
Finish the sentence “this group is unusual compared with …”. The whole index is a cheap default. A background filter gives a more apt comparison, at more cost.
Q9Why is a custom background slower?
The default background counts are precomputed document frequencies in the index. A filtered background requires running a query for each candidate term.
Q10Can I use it on text fields?
Use the significant text aggregation, which analyzes text on the fly and does not need fielddata. It works best with a sampler and duplicate filtering.
Q11What is a sampler for?
It limits the foreground to the best-matching documents on each shard, which saves time and memory and reduces noise from loosely related documents. Diversified and random samplers exist for other needs.
Q12Why are the results approximate?
Each shard sends only its best candidate terms, using local counts. A term that ranks well overall but not on any shard can be missed. A larger shard size reduces this risk.
Q13Why did two runs give slightly different results?
Different replicas have different segments and statistics, live data changes, and sampling can be random. Use absolute time windows, stable preferences, and fixed seeds for repeatability.
Q14Does a significant term prove a cause?
No. It shows that a term and a group tend to occur together. Verify with example documents, timelines, controls, and experiments before drawing conclusions.
Q15How can I use it for recommendations?
Make the foreground the users who liked an item, the background all users, and aggregate over the items they liked. The result is items that are unusually popular among that group, not merely popular overall.
Q16Can I nest it inside other aggregations?
Yes, inside terms, date histogram, and filters aggregations, for example. Each parent bucket becomes a foreground. Nesting multiplies the cost, so keep it small.
Q17What limits protect the cluster?
A bucket limit per request, circuit breakers for memory, and search timeouts. Long analyses can be run asynchronously.
Q18Is it safe on sensitive data?
Only with care. Summaries over small groups can reveal individuals, and background statistics may include documents a user cannot see. Use high minimum counts, restricted access, tests with restricted users, and audit logs.
Q19Does it work well on high-cardinality fields?
It can, but memory and noise grow with the number of distinct values. Prefer categorical fields of moderate cardinality, and avoid unique identifiers.
Q20Do options and defaults change between versions?
Yes. Available heuristics, defaults, sampling options, and related aggregations have evolved. Always confirm in the documentation for the exact version you run.

23Summary and Key Takeaways

If you skim only one part of this guide, make it this one.

The significant terms aggregation finds what is different about a group. It compares the terms in a foreground of documents with a background population, scores each term by how surprising its frequency is, and returns the most surprising ones. It uses the index’s own statistics to make the comparison cheap, and it rewards care: a well-chosen background, sensible evidence floors, sampling, and a habit of verifying every lead.

Key Takeaways

  • What it is: a bucket aggregation that returns terms unusually frequent in a foreground group compared with a background population, ranked by a statistical score.
  • How it works: each shard counts terms in its foreground, reads background counts from term statistics, scores with a heuristic, and sends its best candidates, and the coordinating node adds the counts and rescores.
  • What decides the answer: the foreground you query, the background you compare with, the heuristic, and the minimum document count. Write the comparison as a sentence before you run it.
  • How to handle text and scale: use the significant text aggregation for free text, sample with a sampler, and control cardinality, nesting, and background filters to keep cost down.
  • How to read results: look at counts and percentages, not only scores, watch for rare terms, redundant terms, and hidden factors, and treat every finding as a lead to verify.
  • How to keep it reliable: check that all shards answered, fix time windows, use adequate shard sizes, repeat before acting, and record requests and results.
  • How to keep it safe: protect small groups with high minimum counts, restrict aggregation rights, test background statistics under document-level security, and log analytical access.