The Matrix Stats Aggregation in Elasticsearch

The Matrix Stats Aggregation in Elasticsearch

A complete, friendly guide to the metric that measures many numeric fields at once, reports their averages, spreads, shapes, and how strongly they move together, how it computes exact answers across shards, and how to use, read, secure, and troubleshoot it in production.

Imagine a café owner who keeps a daily record of three numbers: the temperature outside, the number of hot chocolates sold, and the number of iced coffees sold. She has a feeling that cold days sell more hot chocolate and fewer iced coffees, but a feeling is not a fact. She could draw graphs on paper for every pair of numbers. Or she could ask one question and receive a small table that says, in plain numbers, how strongly each measure moves with each of the others.

That small table is what the matrix stats aggregation gives you in Elasticsearch. You name several numeric fields, and Elasticsearch reads all matching documents once and returns, for every field, its count, average, spread, and shape, together with a table showing how every field relates to every other field. It turns a pile of numbers into a compact answer to the question, “Which of these things move together?”

In this guide you will learn what the matrix stats aggregation is, which statistics it reports and what each one means, how it is computed exactly across many shards, how to use it inside groups, how to read its results without fooling yourself, and how to operate it safely in production. You do not need any statistics background. Every new word is explained the first time it appears, and each big idea comes with an everyday comparison.

1What Is a Matrix Stats Aggregation?

The shortest possible answer: it is a metric aggregation that computes descriptive statistics for several numeric fields together, including covariance and correlation between every pair of fields.

Let us build the definition slowly. Elasticsearch is a search and analytics engine. Companies use it to search products, explore logs, count events, and draw charts. Data lives in indices, which are like big labeled cabinets of documents, and each index is cut into pieces called shards so that many servers can share the work.

An aggregation is a way of asking Elasticsearch to summarize many documents into a few numbers or groups, instead of listing the documents themselves. A metric aggregation is a kind of aggregation that calculates numbers from field values: the average price, the highest temperature, the total number of bytes. The matrix stats aggregation is a metric aggregation with a special talent. It works on several fields at the same time, and it reports how those fields relate to each other.

It reports two kinds of things. For each field alone, it reports the count of values, the mean (the average), the variance (how spread out the values are), the skewness (whether the values lean to one side), and the kurtosis (whether the values have heavy tails). For each pair of fields, it reports the covariance and the correlation, which say how the two fields vary together. Because the pairwise numbers form a square table, with one row and one column for every field, the aggregation is called a matrix.

Everyday Analogy

Think of a coach who watches a whole team of runners and notes three things for each runner: height, stride length, and race time. Looking at each number alone is useful, but the coach really wants to know whether taller runners tend to have longer strides and faster times. A single report that lists each measure’s average and spread, and also a small table showing how each measure moves with the others, is exactly what the matrix stats aggregation produces.

Many fields
Several numeric fields are analyzed together in one request
One pass
The documents are read once, and all statistics are computed together
Every pair
Covariance and correlation are reported for each pair of fields
i
Name check

People say “matrix stats,” “matrix_stats,” and “the matrix aggregation.” All of them refer to the same feature. It is not related to matrix mathematics used in machine learning models. The word “matrix” only describes the table of pairwise results.

What it is not

The matrix stats aggregation does not find the highest or lowest value, does not compute a sum, and does not give percentiles. It does not draw charts, and it does not prove that one thing causes another. It also does not work on text. It gives a compact statistical portrait of numeric fields, and it leaves the interpretation to you.

Where you will meet it

You will meet the matrix stats aggregation when an analyst wants to know whether price, rating, and sales move together across a product catalog, when an operations team wants to see whether CPU load, memory use, and response time rise and fall in step, when a factory studies which sensor readings are linked to defects, and when a data scientist wants a quick first look at which numeric fields might be useful for a model. In each case, it answers “which of these move together?” in one request.

2Why It Exists: Looking at Fields Together

Most aggregations look at one field at a time. But many real questions are about relationships between fields, and answering them by other means is slow and clumsy.

Elasticsearch offers many single-field summaries. The average of a price field tells you the typical price. The stats aggregation adds the minimum, maximum, and sum. The extended stats aggregation adds spread. These are valuable, but each of them looks at one field in isolation. They cannot tell you whether expensive products also tend to get high ratings, or whether busy servers also tend to answer slowly.

The old ways of studying relationships

  • Export and analyze elsewhere. Pull millions of documents out of Elasticsearch into a statistics tool. This is slow, moves a lot of data, and creates copies that must be protected.
  • Many separate requests. Ask for the average of each field, then compute the relationships by hand. This gets the averages but not the co-movement, which needs values from the same document at the same time.
  • Custom scripts. Write a scripted metric aggregation that accumulates sums of products. This works, but the script is long, slow, and easy to get wrong.

The matrix stats answer

The matrix stats aggregation moves the calculation to where the data already lives. Every shard computes its share of the statistics while reading its own documents, and the coordinating node merges the shares into an exact final answer. Only a tiny table of numbers travels back to you, no matter how many millions of documents were analyzed.

Everyday Analogy

Imagine a large school with many classrooms, and the principal wants to know whether students who read more also score higher on tests. She could ask every teacher to send all the student records to her office, which is heavy and slow. Or she could ask each teacher to compute a few running totals in their own classroom and send just those totals. She then combines the totals into one answer. The second way is what the aggregation does.

An illustrative story

BrewBeat, an imaginary café chain

BrewBeat stores one document per shop per day, with fields for the temperature, the number of hot drinks sold, the number of cold drinks sold, and the shop’s foot traffic. The analyst wants to know which of these move together. Before, she exported forty million rows into a spreadsheet tool every month, which took hours. With the matrix stats aggregation, one request returns the averages, spreads, and the full correlation table in a couple of seconds, and it can be repeated for each region. The story is invented, but the pattern is one that analysts meet constantly.

A short history

The matrix stats aggregation arrived in Elasticsearch 5.0 as a module of its own, next to the core aggregations. It is bundled with the standard distribution, so no extra plugin is needed in normal installations. Its design uses running totals that can be merged across shards, which is why the result is exact rather than approximate. The details of parameters and defaults have stayed stable, though it is wise to confirm them in the documentation for the version you run.

!
Do not expect miracles

A correlation table is a first look, not a conclusion. It tells you which fields move together in the documents you selected. It does not say why. Chapter 15 explains the traps that lead careful people to wrong conclusions from correct numbers.

3The Building Blocks You Need to Know First

To follow the rest of this guide you need eight simple ideas: aggregation, metric, bucket, doc values, numeric field, shard, doc count, and statistic.

Aggregation

A summary of many documents

Instead of returning documents, an aggregation returns computed results such as counts, averages, or groups.

Metric

A number computed from field values

Metric aggregations produce numbers, such as an average or a statistic. Matrix stats is a metric aggregation that produces many numbers.

Bucket

A group of documents

Bucket aggregations sort documents into groups, such as one per category or per day. Metrics can be computed inside each group.

Doc values

A column store of field values

Elasticsearch keeps a compact, column-like copy of most field values on disk. Aggregations read these values quickly.

Numeric field

A field that holds numbers

Integers, decimals, and similar types. The matrix stats aggregation works on these fields.

Shard

One slice of an index

Each shard computes its own partial statistics. The coordinating node merges them into the final result.

Doc count

How many documents were used

The response tells you how many documents entered the calculation, which is a key sanity check.

Statistic

A number that describes data

Examples are the mean, the variance, and the correlation. Each answers a specific question about the values.

Query and aggregation work together

A search request can contain a query, which chooses which documents to look at, and an aggregation, which summarizes them. The aggregation only sees the documents that match the query. So a request can ask for “the correlation between price and rating for products in the shoes category that are in stock.” The query narrows down the documents, and the aggregation studies them.

The path of an aggregation request

The diagram shows how a request travels. The client usually reaches the cluster through a load balancer or an API gateway, which passes the request to a coordinating node. The coordinating node asks every shard to compute partial results and then merges them.

flowchart LR
    A["Client application"] --> B["Load balancer or API gateway"]
    B --> C["Coordinating node"]
    C --> D1["Shard 1: partial statistics"]
    C --> D2["Shard 2: partial statistics"]
    C --> D3["Shard 3: partial statistics"]
    D1 --> E["Coordinating node merges the partial statistics"]
    D2 --> E
    D3 --> E
    E --> F["Small result table returned to the client"]
Figure 1: Every shard reads its own documents and returns a tiny set of running totals. The coordinating node merges them into the final statistics.
Everyday Analogy

Think of a national census. Each town counts its own residents and reports a few totals to the capital. The capital never sees individual households. It adds up the totals from all towns and announces the national figures. Shards are the towns, the running totals are the reports, and the coordinating node is the capital.

i
Good to know

Because only small totals move over the network, the cost of returning results does not grow with the number of documents. The work of reading the values does, which Chapter 16 explains in detail.

4Statistics Refresher, Part One: Mean, Variance, and Spread

The first statistics describe each field on its own: where its values sit, and how widely they are scattered.

The count

The count is simply how many values of a field entered the calculation. In the matrix stats aggregation, it is important to check the count, because documents that lack a value can be left out, as Chapter 11 explains. A count much smaller than you expected is a warning that something is being skipped.

The mean

The mean is the ordinary average: add all values and divide by how many there are. It tells you where the values are centered. If the temperatures of a week are 10, 12, 14, 12, and 12 degrees, the mean is 12.

The variance

The variance measures how far values typically lie from the mean. To compute it, take each value’s distance from the mean, square that distance, add the squares, and divide by one less than the count. Squaring makes all distances positive and gives extra weight to large ones. A small variance means the values huddle near the mean. A large variance means they are scattered.

DayTemperatureDistance from the mean of 12Squared distance
Monday10-24
Tuesday1200
Wednesday1424
Thursday1200
Friday1200
Total6008

The squared distances add up to 8. Dividing by the count minus one, which is four, gives a variance of 2. The units of variance are the square of the original units, so this variance is in “degrees squared,” which is awkward to picture. That is why people often take its square root, called the standard deviation. Here, the standard deviation is about 1.41 degrees. The matrix stats aggregation reports the variance, and you can take the square root yourself.

Everyday Analogy

Picture two archers shooting at a target. Both average right at the center. The first archer’s arrows land in a tight cluster near the middle, so the variance is small. The second archer’s arrows are scattered all over the target, even though they still average out to the center, so the variance is large. The mean says where the archers aim, and the variance says how steady they are.

Sample versus population

Statisticians divide by the count minus one, not the count, when the values are a sample of a bigger population. This makes the estimate of the spread slightly larger and more honest for small samples. The matrix stats aggregation reports the sample form, so with very few documents, the numbers include this small correction. With millions of documents, the difference is negligible.

What the aggregation does not report

The matrix stats aggregation does not report the minimum, the maximum, the sum, or the standard deviation. If you need them, use the stats or extended stats aggregations on single fields, or compute the standard deviation from the variance. Chapter 14 compares these aggregations.

A caution about the mean

The mean is sensitive to extreme values. One huge outlier can pull it far away from where most values lie. The variance is even more sensitive, because it squares the distances. Keep this in mind when the data contains rare giant values, such as an order worth a million among orders worth fifty.

i
Practical rule

Always read the mean and the variance together. A mean alone hides how scattered the values are, and a variance alone hides where they are centered. Two fields with the same mean and very different variances behave very differently in practice.

5Statistics Refresher, Part Two: Skewness and Kurtosis

Two more statistics describe the shape of a field’s values: whether they lean to one side, and whether they have unusually heavy tails.

Skewness: leaning to one side

Skewness measures the lopsidedness of the values. If the values are balanced around the mean, like a symmetric hill, the skewness is close to zero. If a long tail stretches to the right, with a few very large values, the skewness is positive. If a long tail stretches to the left, with a few very small values, it is negative.

Skewness valueShapeEveryday example
Close to zeroBalanced on both sides of the meanHeights of adults in a large group
Clearly positiveA long tail of large values on the rightHousehold incomes, order values, response times
Clearly negativeA long tail of small values on the leftScores on an easy exam, where most students score near the top
Everyday Analogy

Imagine a ski slope with a gentle beginner side and a very long steep side stretching far into the distance. A snapshot of skiers on the slope would show most people near the top of the gentle side, and a few scattered far down the long side. That long stretch is a skewed tail. Skewness is the number that tells you how long and on which side the tail is.

Why skewness matters

Many real measures, such as response times, prices, and file sizes, are strongly skewed to the right. For such fields, the mean is pulled toward the tail and can be misleading, and the variance is dominated by rare large values. A large positive skewness is a hint to look at percentiles or to consider a transformation, such as taking logarithms, before comparing fields.

Kurtosis: how heavy the tails are

Kurtosis measures how much of the spread comes from rare, extreme values in the tails, compared with a standard bell-shaped curve. A field with high kurtosis has “heavy tails”: most values cluster near the mean, but occasionally extreme values appear. A field with low kurtosis has “light tails”: the values stay within a narrow band, with few surprises.

The matrix stats aggregation reports the plain kurtosis, for which a perfect bell-shaped, or normal, distribution gives a value of about three. Some tools subtract three to report the “excess” kurtosis. Check the documentation of your version to be sure which form is reported, and compare like with like.

Kurtosis (plain form)TailsWhat it suggests
About 3Similar to a normal bell curveExtreme values are as rare as the bell curve predicts
Well above 3Heavy tailsRare, extreme values matter: risk, outliers, or bursts
Well below 3Light tailsValues are held within a narrow range, with few surprises
Everyday Analogy

Think of two towns with the same average daily rainfall. In the first, it drizzles a little almost every day. In the second, it is dry most days, but once in a while there is a violent storm. The averages match, but the second town has heavy tails, and its high kurtosis warns you that the rare storms deserve your attention.

Use the shape statistics with care

  • They need lots of data. With few documents, skewness and kurtosis jump around wildly. Trust them only with a large count.
  • They are sensitive to outliers. Kurtosis uses fourth powers, so a single extreme value can dominate it.
  • They are descriptive. They tell you the shape, not the reason for it.

Why the aggregation reports them together

The shape of each field matters for interpreting the relationships between fields. The correlation that comes later in the response is most meaningful when the fields are not wildly skewed or heavy-tailed. By returning shape statistics next to the correlations, the aggregation lets you check this without a second request.

!
A warning sign

If a field has a very high skewness or kurtosis, treat its correlations with suspicion. A handful of extreme documents may be driving the whole relationship. Try filtering out the extremes or transforming the field, and see whether the correlation survives.

6Statistics Refresher, Part Three: Covariance and Correlation

These two statistics are the reason the aggregation exists. They measure how two fields move together, one in raw units and one on a friendly scale from minus one to plus one.

Covariance: do they move together?

The covariance of two fields looks at each document and asks, “Is the first field above its mean while the second is also above its mean, or is one above and the other below?” For each document, it multiplies the two distances from the means. If both are above or both are below, the product is positive. If one is above and the other below, the product is negative. The covariance is the average of these products, again dividing by the count minus one.

  • A positive covariance means that when one field is high, the other tends to be high too.
  • A negative covariance means that when one field is high, the other tends to be low.
  • A covariance near zero means that no straight-line pattern of moving together shows up.

The trouble with covariance is that its size depends on the units. The covariance between height in centimeters and weight in kilograms is a different number from the covariance between height in meters and weight in grams, even though the relationship is the same. So the raw number is hard to judge by itself. The sign is meaningful, the size is not easily comparable.

Correlation: the friendly scale

The correlation fixes the units problem. It divides the covariance by the product of the two standard deviations, which strips away the units and squeezes the result into a range from minus one to plus one. This is the Pearson correlation coefficient, the most widely used measure of straight-line relationships.

Correlation valueReading in everyday words
Exactly +1A perfect rising straight line: when one goes up, the other goes up in exact proportion
About +0.7 to +0.9A strong tendency to rise together
About +0.3 to +0.5A moderate tendency to rise together
Close to 0No straight-line relationship
About -0.3 to -0.5A moderate tendency for one to fall when the other rises
About -0.7 to -0.9A strong tendency for one to fall when the other rises
Exactly -1A perfect falling straight line

These bands are rules of thumb. What counts as “strong” depends on your field of work: in physics, 0.9 may be weak, and in the study of human behavior, 0.3 may be interesting.

Everyday Analogy

Picture two dancers on a stage. If they always step forward and backward together, they are strongly positively related. If one always steps forward when the other steps back, like partners in a mirror, they are strongly negatively related. If each dances to a different song, there is no relationship. Correlation is a number that says how well the dancers keep step, with the sign telling you whether they move in the same direction or opposite ones.

The matrix of relationships

When you study several fields, you can ask about every pair. With three fields, there are three distinct pairs, and the results can be arranged in a square table with one row and one column for each field. The diagonal of this table compares each field with itself, which always gives a correlation of exactly one. The table is symmetric: the value for the first field against the second equals the value for the second against the first.

CorrelationTemperatureHot drinks soldCold drinks sold
Temperature1.00-0.820.87
Hot drinks sold-0.821.00-0.75
Cold drinks sold0.87-0.751.00

The numbers in this table are invented to illustrate how to read it. Warm days go with fewer hot drinks and more cold drinks, and hot and cold sales trade off against each other. One glance at the table tells the whole story.

Why the number of pairs grows quickly

With two fields there is one pair, with three fields three pairs, with four fields six, with ten fields forty-five, and with twenty fields one hundred and ninety. The number of pairs grows with the square of the number of fields. This is the main reason why the cost of the aggregation grows quickly as you add fields, which Chapter 16 discusses.

What the covariance and correlation of a field with itself mean

The response includes each field’s relationship with itself. The covariance of a field with itself is its variance, and the correlation of a field with itself is one. These entries are not new information, but they make the tables complete and easy to read as matrices.

i
Practical rule

Use the correlation to judge how strong a relationship is, and use the covariance only when you need the raw amount of joint variation, for example as an ingredient in a further calculation. For reading and reporting, the correlation is almost always the better number.

7Anatomy of a Matrix Stats Request

The request has only a few parts. Knowing each one, and the rules it must follow, prevents almost every beginner error.

A matrix stats request is an ordinary search request with an aggregation section. Inside the aggregation section, you give the aggregation a name of your choice, then choose the type, matrix stats, and list its settings. The most common pattern is to set the number of returned documents to zero, since you want only the statistics and not the documents themselves.

Part of the requestRoleRules and notes
QueryChooses which documents are analyzedOptional. Without it, all documents of the target indices are used.
SizeNumber of documents to return with the responseUsually zero, because only the statistics are wanted
Aggregation nameYour label for the resultAny name you like. The response uses it as the key.
FieldsThe list of numeric fields to analyzeRequired. Use several fields for pairwise results.
ModeHow to pick one value when a document has several in a fieldOptions are average, minimum, maximum, sum, and median. The default is the average.
MissingDefault values for documents that lack a fieldA map from field name to value. Without it, documents lacking a listed field are skipped.
Everyday Analogy

Think of an order form at a research lab. You write which group of samples to test, which measurements to take from each sample, what to do when a sample has several readings, and what value to assume when a reading is missing. The lab returns one summary sheet. The fields are the measurements, the mode is the rule for several readings, and the missing setting is the rule for gaps.

Choosing the fields

List only the fields you really want to compare. Because the number of pairs grows with the square of the number of fields, a long list makes the request heavier and the response bigger. A good habit is to start with a small group of fields that you have a reason to compare, such as price, rating, and sales, and not to throw every numeric field into the list.

The narrowing query

The query controls which documents are analyzed, and therefore what the statistics mean. A correlation between price and rating over all products is a different fact from the same correlation over shoes only, or over the last thirty days. Always be clear about the population you are describing. Filtering by time, region, category, or status is very common.

Placement within a bigger aggregation

The matrix stats aggregation can be placed at the top level, or nested inside a bucket aggregation, so that separate statistics are computed for each group. This is a powerful way to compare relationships across groups, and Chapter 13 covers it in detail.

What is not available

  • No scripts. The aggregation works on real, indexed field values, not on values computed by scripts. If you need a calculated value, store it in a field at indexing time, or use a runtime field where your version allows it, and consider the extra cost.
  • No text fields. Only numeric fields are accepted.
  • No per-field options beyond the missing value. The mode applies to all listed fields.

The module behind it

The aggregation lives in a module of Elasticsearch called the matrix stats module. In standard distributions, this module is installed and enabled, so you do not add anything. In customized or minimal builds, it may be absent, and the request would then fail with an error saying that the aggregation type is unknown.

i
Start small

Begin with two fields and a narrow query, check that the results make sense, and only then widen the set of fields or the population. Small requests are quick to run and easy to verify by hand.

8Anatomy of the Response

The response is a compact report. Each field gets its own entry, and inside each entry, pairwise results are listed by the names of the other fields.

The result appears under the name that you gave the aggregation. It contains a top-level count of documents, followed by a list with one entry per field.

Item in the responseWhat it containsHow to read it
Document countThe number of documents that entered the calculationCompare with the number of documents that match your query. A big gap means documents were skipped.
Field listOne entry for each field that you namedRead each entry as the portrait of one field
NameThe field nameIdentifies the entry
CountThe number of values of this field that were usedUsually equals the document count
MeanThe average of the fieldWhere the values are centered
VarianceThe sample varianceHow scattered the values are, in squared units
SkewnessThe lopsidedness of the valuesPositive means a long right tail, negative a long left tail
KurtosisThe heaviness of the tailsCompare with the value for a normal curve, about three in the plain form
Covariance mapThe covariance of this field with each field, itself includedLook up the partner field by name
Correlation mapThe correlation of this field with each field, itself includedThe main result: values from minus one to plus one
Everyday Analogy

Think of a set of player cards in a sports collection. Each card shows one player’s own numbers, such as average, consistency, and playing style, and on the back, a short list of how that player performs alongside each teammate. The response is a deck of such cards, one for each field, with the “performance with each teammate” list being the covariance and correlation maps.

Building the matrix yourself

The response lists correlations inside each field entry, keyed by the partner’s name. To show a familiar matrix table, take the correlation map of each field and arrange them as rows. The rows and columns should list the fields in the same order. Because the table is symmetric, the entry for the first field against the second equals the entry for the second against the first, which gives a handy self-check: if the two disagree, something is wrong with your assembly, not with the data.

When numbers cannot be computed

Some statistics are undefined in certain situations. With fewer than two documents, the variance cannot be computed, because it divides by the count minus one. If a field has the same value in every document, its variance is zero, and any correlation involving it is undefined, since it would divide by zero. In such cases, the response may show null or a special not-a-number marker for those entries. Treat them as “not enough information,” not as zeros.

The number of decimals

Values are returned as floating point numbers with many digits. Round them for display, and remember that tiny differences in the last digits are normal, as Chapter 17 explains. Do not compare two results for exact equality; compare them with a small tolerance.

Checking the document count

The single most useful sanity check is to compare the document count in the response with the number of documents that your query matches. You can obtain that number with an ordinary count of the same query. If the aggregation used far fewer documents, some of them lack a value in one of the listed fields, and the statistics describe only the subset that has all of them.

!
A silent trap

A response with a comfortable-looking correlation table can hide the fact that only a small share of documents were used. Always read the count before you read the correlations.

9A Worked Example: Five Documents by Hand

Numbers make the method concrete. Here is a complete calculation with five documents and two fields, so that you can see where every reported number comes from.

Imagine five documents, each with two numeric fields. The first field is the number of hours that a customer spent on a tutorial, and the second is the score that the customer received on a quiz. The data are small on purpose, so that the arithmetic is easy to follow.

DocumentHours (x)Score (y)
112
224
335
444
555

Step one: the means

The hours add up to 15, so the mean is 3. The scores add up to 20, so the mean is 4.

Step two: the distances from the means

Documentx minus 3y minus 4(x minus 3) squared(y minus 4) squaredProduct of the two distances
1-2-2444
2-10100
301010
410100
521412
Total001066

Step three: the variances and the covariance

Divide each total by the count minus one, which is four. The variance of the hours is 10 divided by 4, which is 2.5. The variance of the scores is 6 divided by 4, which is 1.5. The covariance is the total of the products, 6, divided by 4, which is 1.5.

Step four: the correlation

Divide the covariance by the square root of the product of the two variances. The product of the variances is 2.5 times 1.5, which is 3.75, and its square root is about 1.936. So the correlation is 1.5 divided by 1.936, which is about 0.775.

StatisticHoursScore
Count55
Mean34
Variance2.51.5
Covariance with hours2.51.5
Covariance with score1.51.5
Correlation with hours1about 0.775
Correlation with scoreabout 0.7751
Everyday Analogy

Think of a teacher who notices that students who study longer usually score higher, but not perfectly: one student who studied four hours scored no better than a student who studied two. A correlation of about 0.775 says exactly that: a fairly strong tendency to rise together, with some students breaking the pattern. A perfect one would mean that every extra hour raised the score by exactly the same amount.

Reading the results

  • The relationship is positive. More hours went with higher scores in this small group.
  • The relationship is strong but not perfect. A value of 0.775 is well above zero and well below one.
  • The sample is tiny. With only five documents, this number could change a lot with one more student. Statistics from tiny samples are fragile.
  • The self-entries are consistent. The covariance of each field with itself equals its variance, and each correlation with itself is one.

What Elasticsearch would return

The response would contain a document count of five and two field entries, named hours and score. Each entry would list its mean and variance, its skewness and kurtosis, and the two maps of covariance and correlation with the numbers above, apart from tiny rounding differences in the last digits. You can verify a real response on a small test index in a couple of minutes, which is a very good way to build trust in the aggregation.

i
Do the test once

Create a small test index with these five documents, run the aggregation, and compare the response with the table above. Once you have seen the numbers match, the aggregation stops being a black box.

10How It Works Inside: Running Statistics and Merging

The aggregation never needs to gather all values in one place. Each shard keeps small running totals, and the totals can be merged exactly.

To compute a correlation directly, you would need every pair of values in one place, which is impossible at large scale. The trick is that all the statistics can be built from a few running totals that are easy to update one document at a time and easy to combine across shards.

1

The request arrives

A coordinating node receives the aggregation with its list of fields, and forwards it to one copy of each relevant shard.

2

Each shard finds its matching documents

The shard runs the query and gets the set of documents that match.

3

The shard reads the values from doc values

For each matching document, it reads the value of every listed field. Documents that lack a value in any listed field are skipped, unless a default value was given.

4

The shard updates its running totals

For each accepted document, it updates the count, the running means, and the running sums of squared and cross-multiplied distances for every field and every pair of fields.

5

The shard returns its partial state

It sends the running totals to the coordinating node. The size of this message depends on the number of fields, not on the number of documents.

6

The coordinating node merges the states

It combines the partial states with a formula that gives the same answer as if all documents had been processed together.

7

The final statistics are computed

From the merged totals, the variances, covariances, correlations, skewness, and kurtosis are calculated and returned.

sequenceDiagram
    participant C as Client
    participant N as Coordinating node
    participant S1 as Shard 1
    participant S2 as Shard 2
    C->>N: Search with a matrix stats aggregation
    N->>S1: Run query and aggregation
    N->>S2: Run query and aggregation
    S1->>S1: Read doc values, update running totals
    S2->>S2: Read doc values, update running totals
    S1-->>N: Partial running totals
    S2-->>N: Partial running totals
    N->>N: Merge totals and compute final statistics
    N-->>C: Count, means, variances, shapes, covariance and correlation maps
Figure 2: Each shard reduces its documents to a tiny set of running totals. The coordinating node merges them and computes the final statistics.
Everyday Analogy

Imagine several accountants who each keep the books for a different branch of a company. To learn the company’s overall profit and how sales relate to costs, the head office does not need every receipt. Each accountant sends a summary sheet of running totals, and the head office combines the sheets with simple arithmetic to get exactly the numbers it would have gotten from all the receipts. The running totals are the summary sheets.

Exact, not approximate

Some aggregations, such as counting distinct values or computing percentiles, are approximate, because their exact versions would need too much memory. The matrix stats aggregation is different: its running totals contain everything needed for the exact answer, so the result is exact, apart from tiny floating point rounding effects. This is a strong point in its favor for analyses where you want the true relationship in the selected documents.

Numerically stable merging

The running totals are kept in a form, based on distances from running means, that avoids the large rounding errors of the naive method of summing squares of raw values. The merge formula is designed to combine two such states without loss of accuracy. This matters especially for fields with large values and small differences, where naive methods can lose all their precision.

Replicas and repeatability

Each shard is queried on one of its copies, and all copies hold the same documents, so the statistics are the same. However, the order in which shard states are merged can differ from run to run, and floating point addition is not perfectly associative, so the last few digits of a result may differ slightly between two identical requests. This is normal and harmless.

What the shard does not keep

The shard does not keep the individual values, only the totals. That is why memory use per shard depends on the number of fields and pairs, not on the number of documents, and why the aggregation can run over hundreds of millions of documents without needing to hold them in memory.

i
Good to know

The work that grows with the data is the reading of doc values and the update of the running totals for each document. The work that grows with the number of fields is the update of the pair totals, which grows with the square of the number of fields.

11Multi-Valued Fields and Missing Values

Real data is messy: fields hold several values, or none at all. The mode and missing settings decide how such documents are treated, and the choices change the answers.

Fields with several values

A field in Elasticsearch may hold an array of numbers in a single document, for example several measurements taken during one visit. The statistics need exactly one number per document per field, so the mode setting chooses how to reduce the array.

ModeValue used from the arrayGood for
Average, the defaultThe mean of the valuesGeneral use, when all readings are equally meaningful
MinimumThe smallest valueStudying the lowest reading, such as the lowest battery level
MaximumThe largest valueStudying peaks, such as the highest temperature
SumThe total of the valuesQuantities that add up, such as the total of several charges
MedianThe middle valueArrays that may contain outliers
Everyday Analogy

Imagine a fitness log where a runner records several heart rates during one run. To compare runs, you need one heart rate per run. You could take the average, the highest, the lowest, or the middle reading. Each choice answers a slightly different question, and the comparison between runs changes with the choice. The mode setting is that choice.

One mode for all fields

The mode applies to every listed field in the aggregation. If you need a different rule for different fields, for example the maximum for one and the average for another, store separate single-valued fields at indexing time, or run separate aggregations.

Documents with missing values

By default, a document that lacks a value in any of the listed fields is skipped entirely for the whole calculation. It does not contribute to the statistics of the fields that it does have. This keeps the pairwise comparisons honest, since every statistic is based on the same set of documents, but it can shrink the sample dramatically if the fields are often missing.

flowchart TD
    A["A matching document is read"] --> B{"Does it have a value in every listed field?"}
    B -->|Yes| C["Reduce multi-valued fields with the mode and add the document to the statistics"]
    B -->|No| D{"Is a default given for each missing field?"}
    D -->|Yes| E["Fill in the defaults and add the document"]
    D -->|No| F["Skip the document entirely"]
Figure 3: A document enters the statistics only if it has a value, or a default, for every listed field.

Supplying default values

The missing setting lets you give a default value for each field, so that documents lacking it are included as if they had that value. This can be useful, for example, to treat a missing “discount” as zero. But it can also distort the results. Filling in values pulls the mean toward the default, shrinks the variance, and can create false relationships. Use defaults only when the default is a truthful value, such as zero for “none,” and not as a way to keep the sample large.

SituationBest treatmentRisk
Missing means truly zero, such as no discountSupply zero as the defaultLow, if zero is really correct
Missing means unknown, such as a rating that was never givenLeave the documents outThe sample shrinks, but the statistics stay honest
Missing values are rareLeave the documents outVery low
Missing values are common and unknownInvestigate why, and consider filtering to complete documents explicitlyBias if the missingness itself is related to the values

Check what was skipped

To see how many documents were skipped, compare the document count in the response with the number of documents matched by the same query. You can also count documents that lack each field with a separate query. Knowing the share of skipped documents is part of interpreting any correlation.

Missing is not always random

If documents lack a value for a reason connected to the thing you study, skipping them biases the result. For example, if premium customers rarely leave ratings, a correlation between price and rating computed only from rated products describes the customers who bother to rate, not everyone. Think about why values are missing before trusting the numbers.

!
Never fill in blindly

Using a default value only to make the document count look larger is a way of inventing data. If you must fill in, document the reason, and test how much the results change with and without the defaults.

12Which Fields Can You Use?

The aggregation is picky about field types. Knowing the rules saves time, and a few modeling choices at indexing time make the results far more useful.

Field typeUsable?Notes
Integer and long typesYesThe most common choice for counts and whole-number measures
Double and float typesYesFloats are converted to doubles, which can expose tiny representation differences
Scaled floatYesStored as scaled whole numbers and reported with their decimals
DateUsually not directlyConvert dates to numbers, such as age in days, hour of day, or a timestamp stored as a number, when you need them
BooleanUsually not directlyStore a zero and one numeric field if you want to study a yes-or-no flag
Keyword and textNoNot numeric. Convert to numbers at indexing time if a numeric meaning exists.
Runtime field with a numeric typePossibly, in versions that support itComputed at query time, so it costs more. Prefer real indexed fields for large analyses.
Everyday Analogy

A calculator works with digits, and it cannot multiply a name by a color. To use it on words, you must first translate them into numbers, like turning “small, medium, large” into 1, 2, 3, if that order truly means something. The matrix stats aggregation needs its inputs already in numeric form.

Doc values must be present

The aggregation reads values from doc values, the column-like store of field values. Numeric fields have doc values by default. If you turned them off for a field to save space, that field cannot be aggregated. Check the mapping when a field is rejected.

Searching several indices

A request can target several indices, such as daily indices of the same data. If a field is mapped as a number in all of them, the aggregation works across them. If a field is a number in some and a keyword in others, the request fails or misbehaves. If a field exists in only some indices, documents from the others lack it and are skipped. Keep mappings consistent across indices that you analyze together.

Choose measures with a meaningful scale

Correlation is unaffected by changing units, but the other statistics are not. Prefer fields whose values are real quantities, such as amounts, durations, and counts. Be careful with codes stored as numbers, such as postal codes, product identifiers, or category numbers. Their arithmetic has no meaning: the average of two postal codes is not a place. A correlation involving such a field is nonsense even if the aggregation happily computes it.

Design fields for analysis

  • Store measures as numbers, not text. A price stored as a text field with a currency symbol cannot be analyzed.
  • Store one clear number per field. Avoid mixing units in one field.
  • Precompute meaningful ratios. A field for “revenue per visit” can be more useful than two separate fields if that ratio is the thing you study.
  • Keep mappings stable. A field whose type changes between indices makes multi-index analysis fragile.

Units and scale

The correlation does not care whether a field is in meters or centimeters. The covariance and the variance do. If you compare covariances between different pairs, make sure the fields use consistent units, or prefer correlations for comparison.

!
Identifiers are not measures

A numeric identifier such as a customer number is only a label. Never include it in a correlation. The aggregation will not stop you, and the result will look like a real number while meaning nothing.

13Using It Inside Bucket Aggregations

Placing the aggregation inside groups lets you ask whether a relationship holds everywhere, or changes from group to group, day to day, or region to region.

A bucket aggregation sorts documents into groups. The terms aggregation makes one bucket for each distinct value of a field, such as each product category. The date histogram aggregation makes one bucket for each time interval, such as each day. The filters aggregation makes buckets from named queries. When you nest a matrix stats aggregation inside a bucket aggregation, Elasticsearch computes a separate set of statistics for each bucket.

flowchart TD
    A["Query selects the documents"] --> B["Bucket aggregation: one group per category, day, or region"]
    B --> C1["Group 1: matrix stats of the chosen fields"]
    B --> C2["Group 2: matrix stats of the chosen fields"]
    B --> C3["Group 3: matrix stats of the chosen fields"]
    C1 --> D["Compare the relationships across groups"]
    C2 --> D
    C3 --> D
Figure 4: A bucket aggregation splits the documents into groups, and each group gets its own statistics and correlation table.
Everyday Analogy

Imagine a school principal who wants to know whether study time and exam scores go together. She could compute one number for the whole school. Or she could compute it separately for each class and see whether the pattern is the same everywhere. If some classes show a strong link and others none, the single school-wide number would have hidden that difference. Nesting the aggregation in buckets is the class-by-class view.

Useful ways to group

  • By category. Does price relate to rating differently for shoes and for electronics?
  • By time. Did the link between load and latency get stronger this week? A date histogram with one bucket per day gives a daily correlation, which you can chart to spot drift.
  • By region or customer segment. Are the relationships the same in every market?
  • By version or experiment group. Did a new release change how metrics move together?

The danger of the overall number: an example

Overall correlations can be badly misleading. Consider two groups of documents. In group A, the field x takes the values 1, 2, and 3, and the field y takes the values 5, 4, and 3. Inside group A, y falls as x rises, with a correlation of exactly minus one. In group B, x takes the values 6, 7, and 8, and y takes the values 10, 9, and 8. Inside group B, y also falls as x rises, again with a correlation of minus one. Now put all six documents together. The group B documents have both higher x and higher y than group A, so across the whole set, y tends to rise with x, and the overall correlation is about plus 0.81.

PopulationValues of xValues of yCorrelation
Group A alone1, 2, 35, 4, 3-1.00
Group B alone6, 7, 810, 9, 8-1.00
Everything together1, 2, 3, 6, 7, 85, 4, 3, 10, 9, 8about +0.81

This reversal is known as Simpson’s paradox. The overall positive number says that x and y rise together, while inside each group, they move in opposite directions. A hidden group difference created the overall pattern. If you only looked at the overall number, you would draw the opposite conclusion from the truth in each group.

Everyday Analogy

Picture two schools. In each school, students who spend more time on video games score slightly lower. But the students of the richer school both play more games, because they own more devices, and score higher, because of better teaching. Put both schools together, and it looks like more gaming goes with higher scores. The school hides the true pattern. Looking inside each school reveals it.

Practical cautions for nested use

  • Small groups give unstable statistics. A correlation from five documents can swing wildly. Use the minimum document count setting of the bucket aggregation to hide tiny groups.
  • The cost multiplies. Each bucket needs its own running totals, so many buckets with many fields add up. Keep the number of buckets and fields reasonable.
  • Bucket limits apply. Elasticsearch limits the total number of buckets in a response. A very fine grouping may hit this limit.
  • Use a composite aggregation for many groups. If you must analyze thousands of groups, page through them in batches with a composite aggregation instead of asking for them all at once.
  • Compare with the overall result. Run the top-level aggregation next to the grouped one, and look for differences in sign or size.
i
A daily correlation chart

Group by day, compute the correlation between two operational metrics for each day, and chart the result over time. A line that suddenly drops or flips sign is often the earliest visible sign that a system has changed its behavior.

14Comparing Matrix Stats with Other Ways to Summarize Numbers

Elasticsearch offers several numeric aggregations. Each answers a different question, and choosing the right one saves effort and avoids wrong conclusions.

Aggregation or toolFields at onceWhat it reportsBest for
Average, sum, minimum, maximumOneA single numberSimple headline figures
StatsOneCount, minimum, maximum, average, and sumA quick overview of one field
Extended statsOneEverything in stats, plus sum of squares, variance, standard deviation, and boundsSpread of one field
PercentilesOneValues below which a chosen share of documents fall, approximatelyTails and service level targets
Matrix statsSeveralCount, mean, variance, skewness, kurtosis, covariance, and correlation for every field and pairRelationships between numeric fields
Scripted metricAnyWhatever your script computesCustom calculations when nothing built in fits, at a higher cost and complexity
Transforms and data analysis jobsManyPrecomputed summaries, and modelsContinuous, repeated analysis and heavier statistics
Export to a statistics toolManyAnything the tool supportsDeep analysis, regression, and charts beyond the aggregation
Everyday Analogy

Think of a toolbox. A tape measure tells you one length. A set of calipers tells you several measures of one object. A tool that compares two objects and tells you how alike they are is a different instrument again. The matrix stats aggregation is the comparison tool: it does not replace the tape measure, but it answers a question that no single-object tool can.

What matrix stats has and lacks

It offers

  • Covariance and correlation between fields.
  • Skewness and kurtosis of each field.
  • Exact results, merged across shards.
  • Several fields analyzed in one pass.

It does not offer

  • Minimum, maximum, sum, or standard deviation.
  • Percentiles or medians of the values.
  • Non-linear or rank-based relationship measures.
  • Significance tests or confidence intervals.
flowchart TD
    A["What do you want to know?"] --> B{"One field or several?"}
    B -->|One field| C{"Need the tails?"}
    C -->|Yes| D["Percentiles"]
    C -->|No| E["Stats or extended stats"]
    B -->|Several| F{"Need relationships between them?"}
    F -->|Yes| G["Matrix stats"]
    F -->|No| H["Separate single-field aggregations"]
    G --> I{"Need regression, tests, or non-linear measures?"}
    I -->|Yes| J["Export or use a dedicated analysis tool"]
    I -->|No| K["Matrix stats is enough for a first look"]
Figure 5: A simple path for choosing a numeric aggregation. Matrix stats is the answer for quick relationships between several fields.

A cross-check with extended stats

To trust your setup, run the extended stats aggregation on one of the fields, and compare its variance with the variance from the matrix stats. They should agree up to the difference between the population form and the sample form of the variance, which is a factor of the count divided by the count minus one. For large counts, they are almost identical. Checking this once builds confidence that you are reading the fields you think you are.

When to leave Elasticsearch

If you need to fit a regression line, test whether a correlation is statistically significant, measure rank correlations that are robust to outliers, or study relationships that are not straight lines, the aggregation is not enough. You can export a sample of the data to a statistics environment and do the deeper analysis there. Use the aggregation to find the promising pairs, and the specialized tool to study them.

A related feature with a similar name

Elasticsearch also has a pipeline aggregation for correlating the shape of a metric across buckets with a reference shape. It answers a different question, such as which terms show a spike in the same time window as an event. Do not confuse it with matrix stats, which correlates several fields within the same documents.

i
Screen first, study later

A good workflow is to use the matrix stats aggregation as a fast screening tool across many candidate fields, then investigate the most interesting pairs with deeper methods. The aggregation is cheap and exact, and it tells you where to look.

15Reading Correlation Wisely: Traps and Cures

The numbers from the aggregation are exact, but they can still mislead. Most wrong conclusions come from reading correct numbers the wrong way.

TrapWhat happensCure
Correlation is not causationTwo fields move together, but neither causes the other, or a third factor drives bothThink about mechanisms, run experiments, and treat correlation as a clue, not proof
OutliersA few extreme documents can create or destroy a correlationCheck skewness and kurtosis, filter or cap extremes, and compare
Non-linear relationshipsA strong curved relationship can show a correlation near zeroLook at scatter plots, and try transforming a field
Simpson’s paradoxA combined correlation reverses inside the groupsCompute correlations per group with nested aggregations
Trends over timeTwo fields that both grow over time look strongly relatedCompare changes instead of levels, or compute within short windows
Small samplesThe correlation swings widely with a few documentsRequire a minimum count, and read the count first
Many comparisonsWith many pairs, some look strong just by chanceLimit the number of fields, and confirm interesting pairs on fresh data
Missing data biasSkipped documents differ from the restCompare the document count with the matching count, and think about why values are missing
Restricted rangeA narrow query hides a relationship that appears over a wider rangeCheck whether your filter cuts the range of the fields

An outlier example with numbers

Take ten documents where x runs from 1 to 10 and y is almost the same, with small ups and downs: 2, 1, 4, 3, 6, 5, 8, 7, 10, and 9. The correlation is about 0.94, a very strong relationship. Now change the last y value from 9 to 60, as if a data error had crept in. The correlation drops to about 0.64, even though nine of the ten documents are exactly as before. One bad document damaged the whole picture.

A curve example

Take seven documents where x runs from minus three to three, and y equals x multiplied by itself: 9, 4, 1, 0, 1, 4, 9. The relationship is perfect and predictable, since y is exactly the square of x. Yet the correlation is exactly zero, because the left half of the curve falls while the right half rises, and the two cancel out. The aggregation reports no straight-line relationship, which is true, but it does not say that there is no relationship at all.

Everyday Analogy

Think of a thermometer that measures only whether a room is getting warmer on average. It says nothing about a room that is warm in the morning, cold at noon, and warm again at night. A zero reading does not mean nothing is happening, only that no steady rise or fall shows up. Correlation is a straight-line thermometer.

Trends and the illusion of connection

Many business measures grow over time: users, revenue, storage, traffic. Two growing measures will correlate strongly simply because both rise with time, even if they have nothing to do with each other. To test a real link, compare their changes from one period to the next, or compute the correlation within short periods where the trend is small.

The multiple comparisons problem

If you put twenty fields into the aggregation, you get one hundred and ninety correlations. Even if no real relationships existed, a handful of them would look notable by pure chance. The more pairs you inspect, the more likely you are to find a striking but false one. Treat surprising discoveries as hypotheses, and check them on new data or a different time period before acting.

A checklist before you trust a correlation

  1. Is the document count large enough, and close to the number of matching documents?
  2. Are the shape statistics of both fields reasonable, without extreme skewness or kurtosis?
  3. Does the relationship hold inside the main groups, and not only overall?
  4. Is there a plausible reason for the relationship?
  5. Does it hold on a different time period or a different sample?
!
Numbers are not conclusions

A high correlation is an invitation to ask questions, not an answer. Decisions that carry cost or risk should never rest on a single correlation from a single request.

16Performance and Scalability

The aggregation reads every matching document once. Its cost grows with the number of documents, and much faster with the number of fields.

The cost model

For each matching document, the shard reads one value for each listed field and updates the running totals for each field and each pair of fields. If there are k fields, the number of pairs is k times k minus one, divided by two. The work per document is therefore roughly proportional to k plus that number of pairs. The table shows how quickly this grows.

Number of fieldsNumber of distinct pairsRelative work per document
21Small
33Small
510Modest
1045About five times the cost of five fields
20190About four times the cost of ten fields
501,225Very heavy, and the response is huge
Everyday Analogy

Consider a party where every guest must shake hands with every other guest. With four guests, there are six handshakes. With ten guests, there are forty-five. With fifty guests, there are one thousand two hundred and twenty-five. Adding one more guest to a big party adds a lot of handshakes. Adding one more field to the aggregation adds a similar number of pair updates.

Levers to keep it fast

LeverEffectNote
Fewer fieldsCuts the work quadraticallyThe most powerful lever
A narrower queryFewer documents to readFilter by time range, category, or status
Filters instead of scoring queriesAvoids scoring work for documents that only need to matchThe aggregation does not need scores
Fewer buckets when nestedFewer sets of running totalsUse a minimum document count and sensible group sizes
Zero returned documentsSkips the fetch phaseSet the size to zero when you only want the statistics
Shard request cacheRepeated identical requests can be answered from a cacheWorks best on indices that are not changing, and for requests without moving time values
Precomputing with a transformMoves repeated heavy work out of dashboardsGood for daily or hourly summaries
Well-sized shardsBalances parallel work against overheadToo many tiny shards add overhead

Scaling with data volume

Because each shard works in parallel on its own documents, the time falls as you add shards and nodes, up to the point where overhead dominates. The merged result is tiny, so the network is rarely a bottleneck. Doubling the number of documents roughly doubles the work per shard, and doubling the number of nodes roughly halves it, when the data is spread evenly.

The role of caches

Doc values are read through the operating system’s file cache. On a warm cache, the aggregation is fast. On a cold cache, it must read from disk, and the first run can be much slower than later runs. When you benchmark, run the request several times and note both the first and the later timings.

Measuring

Every response reports how long it took. Compare the time with a simple aggregation on a single field over the same documents, to see how much the extra fields cost. If the time is larger than expected, profile the request or test it with fewer fields to find the growth.

i
Practical rule

Keep the field list short and the population narrow. For a dashboard, keep to a handful of fields and a time range, and precompute the rest. Broad, many-field requests over the whole history are best run occasionally, at quiet times.

17Memory, Precision, and Numerical Limits

The aggregation uses very little memory, but numbers on computers have limits. Knowing them helps you spot results that look wrong for technical reasons.

Memory is small

The running state for one calculation consists of a count, a few numbers per field, and a few numbers per pair of fields. With twenty fields, that is a few hundred numbers, a few kilobytes at most. The state does not grow with the number of documents. This is why the aggregation is safe to run over huge indices, and why memory circuit breakers rarely trip because of it. Nested use with very many buckets multiplies the state by the number of buckets, which can matter.

Floating point numbers

Computers store decimal numbers as floating point values with a limited number of digits, about fifteen to seventeen significant digits for the standard double precision. This is plenty for most analyses, but it has consequences.

  • Tiny rounding differences. Adding numbers in a different order can change the last digits. Two identical requests may differ in the fifteenth digit.
  • Float fields are widened. A field stored as a single-precision float, holding a value such as 0.1, is converted to double precision with a slightly different value, like 0.10000000149. This is harmless for statistics but visible if you compare exactly.
  • Huge values. Skewness and kurtosis involve third and fourth powers, so values with very large magnitudes can overflow or lose precision. Consider scaling such fields, for example by expressing bytes in megabytes.
Everyday Analogy

A calculator with a ten-digit display can show a small difference between two large numbers only if the digits reach far enough. If you subtract two numbers that agree in their first nine digits, the result may be mostly noise. Good statistical methods are careful to avoid such subtraction, and the aggregation’s running totals are designed that way, but extreme data can still challenge any calculator.

Constant and near-constant fields

A field that has the same value in every document has zero variance, and its correlations with other fields are undefined. A field that varies only a tiny bit may have a huge relative rounding error. If you see null or not-a-number results for a field, check whether it is constant in the population you selected. This often happens after a narrow filter.

Very small samples

With one document, the variance cannot be computed. With two documents, any correlation is exactly plus one or minus one, since two points always lie on a straight line. With a handful of documents, skewness and kurtosis are almost meaningless. Always look at the count before you interpret the shape statistics.

Scale matters for some statistics

Multiplying a field by a constant changes its variance and its covariances with other fields, but leaves its correlations, skewness, and kurtosis unchanged. This is why correlation is the right number for comparing relationships across fields with different units.

Transforming skewed fields

For fields with strong positive skewness, such as amounts and durations, a common practice is to work with the logarithm of the values. The logarithm compresses the long tail and often makes relationships look more like straight lines. You can store the transformed value in its own field at indexing time. Be sure to remember that the correlation is then about the logarithms, not the original values.

Sanity checks that catch technical problems

  • Run the aggregation on a tiny hand-checkable set, as in Chapter 9.
  • Compare the variance with the one from extended stats.
  • Check that the correlation of a field with itself is one, and that the matrix is symmetric.
  • Confirm that all correlations lie between minus one and plus one, allowing for tiny rounding.
!
Values outside the range

A correlation slightly above one or below minus one, by a hair, is a rounding artifact and can be treated as one or minus one. A value far outside the range means something is wrong with the data or the reading of the response.

18Advantages, Disadvantages, and Trade-offs

No tool is perfect. Here is an honest scorecard so that you can decide when to use the aggregation and when to look elsewhere.

Advantages

  • Computes relationships between several fields in one request, near the data.
  • Returns exact results, because the running totals merge without approximation.
  • Moves only a tiny table over the network, however many documents are analyzed.
  • Uses very little memory, independent of the number of documents.
  • Works inside bucket aggregations for group-by-group comparisons.
  • Reports shape statistics that help judge whether correlations are trustworthy.
  • Needs no export, so no extra copies of data are created.
  • Is included in standard distributions with no extra plugin.

Disadvantages

  • Cost grows with the square of the number of fields.
  • Measures only straight-line relationships, using the Pearson method.
  • Is sensitive to outliers and skewed data.
  • Skips documents that lack any listed field, which can shrink and bias the sample.
  • Offers no significance tests, confidence intervals, or regression.
  • Does not report minimum, maximum, sum, or standard deviation.
  • Does not accept scripts, text fields, or, in many versions, dates directly.
  • Invites over-reading, since correlations look precise and authoritative.

The central trade-off: convenience against depth

The aggregation gives a very quick, cheap, in-place look at relationships. In exchange, it offers only the simplest measure of association. For a first screening, this is ideal. For research-grade analysis, it is a starting point.

The second trade-off: breadth against cost

Adding fields reveals more relationships, but the cost and the number of chance findings both grow quickly. A focused list of fields chosen for a reason usually beats a broad sweep.

The third trade-off: completeness against honesty

Skipping documents with missing values keeps every statistic based on the same complete set, but it shrinks the sample and may bias it. Filling in defaults keeps the sample large but may invent relationships. Neither is free, and the right choice depends on what missing means in your data.

The fourth trade-off: the overall view against the group view

One correlation over everything is simple to report but may hide group differences. Correlations per group are richer but multiply the cost and produce many numbers to interpret. Use both, and compare them.

When matrix stats is the wrong tool

If you need to understand a curved relationship, test significance, or fit a model, use a statistics environment. If you only need one field’s spread, use extended stats. If you need tails, use percentiles. If you need the same summary every hour for a dashboard, precompute it with a transform. Use the aggregation where its strengths apply.

19Best Practices and Design Patterns

Good use of the aggregation is mostly a matter of a few habits, chosen before the first request. These eight cover almost every case.

Pattern 1

Choose a small, purposeful field list

List only the fields that you have a reason to compare. Every extra field adds cost and adds chances for chance findings.

Pattern 2

Define the population with a query

Always state which documents are analyzed: a time range, a category, a status. A correlation without a stated population is hard to interpret.

Pattern 3

Read the counts first

Compare the document count with the number of matching documents before you look at any correlation.

Pattern 4

Store analysis-friendly numbers

Keep measures in numeric fields with clear units, and precompute useful ratios and transformed values at indexing time.

Pattern 5

Compare overall and per group

Run the aggregation at the top level and nested inside meaningful groups, and look for reversals and differences.

Pattern 6

Precompute for dashboards

For repeated views, compute summaries on a schedule with a transform and read the stored results.

Pattern 7

Screen first, study later

Use the aggregation to find promising pairs, then examine those pairs with scatter plots and deeper statistical tools.

Pattern 8

Guard with minimum group sizes

Hide groups with too few documents, both for statistical stability and for privacy.

Pattern 5 in action

An analyst at an online store sees a correlation of about plus 0.4 between the price and the rating of products, and is ready to report that customers rate expensive products higher. Before doing so, she nests the aggregation inside a terms aggregation by category. In eight of the ten largest categories, the correlation is close to zero or slightly negative. The overall positive number came from the fact that categories with higher prices, such as electronics, also happen to have higher average ratings. She reports the category-level finding instead, which is more accurate and more useful.

Pattern 6 in action

An operations team wants a daily chart of the correlation between request rate, CPU load, and response time for each service. Running the aggregation over months of data for dozens of services every time someone opens the dashboard would be heavy. They create a transform that computes the daily statistics for each service once, stores them in a small summary index, and lets the dashboard read from it. Page loads drop from seconds to milliseconds, and the cluster load from the dashboard nearly disappears.

Pattern 7 in action

A factory records sixty sensor readings for every manufactured part, plus a numeric defect score. The engineers cannot examine all pairs at once, so they screen in batches of six fields, always including the defect score. They keep the pairs with the strongest and most stable correlations, then export samples of those and study them with scatter plots and regression tools. The aggregation narrowed the search from thousands of pairs to a handful.

A pattern for documentation

For each analysis that you share, record the query, the fields, the mode and missing settings, the document count, the date, and the version of the data. A correlation without this context cannot be reproduced or challenged, and it tends to be quoted long after its context is forgotten.

i
Keep it boring

The most trustworthy analyses are usually the simplest: a few well-chosen fields, a clear population, the counts checked, and the result confirmed on another slice of data. Cleverness in this area often hides mistakes.

20Anti-Patterns and Common Mistakes

These are the traps behind most disappointing analyses. Each is common and easy to avoid once you know it.

ANTI-PATTERN 01Avoid
What people do

They list dozens of numeric fields “to see what correlates with what.”

Why it hurts

The cost grows with the square of the number of fields, the response becomes huge, and among hundreds of pairs, some look striking purely by chance.

Better approach

Choose a handful of fields for a reason, or screen in small batches, and confirm findings on fresh data.

ANTI-PATTERN 02Avoid
What people do

They read the correlations without checking how many documents were actually used.

Why it hurts

Documents that lack any listed field are skipped, so the statistics may describe only a small, unrepresentative subset.

Better approach

Compare the document count with the number of matching documents, and investigate large gaps.

ANTI-PATTERN 03Avoid
What people do

They include numeric identifiers, codes, or category numbers as if they were measurements.

Why it hurts

The arithmetic on labels has no meaning. The aggregation computes a number happily, and the number is nonsense.

Better approach

Use only fields that measure a real quantity, and never correlate labels.

ANTI-PATTERN 04Avoid
What people do

They fill missing values with zeros or averages to keep the sample large.

Why it hurts

The invented values pull means toward the default, shrink variances, and can create relationships that do not exist.

Better approach

Fill in only when the default is truthful, such as zero meaning none. Otherwise, leave documents out and report the smaller count.

ANTI-PATTERN 05Avoid
What people do

They report a single overall correlation and stop.

Why it hurts

Hidden groups can reverse or create the pattern, as in Simpson’s paradox, and the reported conclusion may be the opposite of the truth inside the groups.

Better approach

Nest the aggregation inside meaningful groups, and compare with the overall number.

ANTI-PATTERN 06Avoid
What people do

They treat a strong correlation as proof of cause and act on it, for example by automating a decision.

Why it hurts

Correlation can come from a third factor, from shared trends, from selection, or from chance. Acting on it can waste money or cause harm.

Better approach

Treat correlation as a clue. Look for a mechanism, test with an experiment, and confirm on new data before acting.

ANTI-PATTERN 07Avoid
What people do

They run a many-field aggregation over the entire history on every dashboard refresh.

Why it hurts

Every refresh reads every document again, and many users can overload the cluster with identical heavy work.

Better approach

Narrow the time range, cache identical requests where possible, and precompute summaries for repeated views.

Other frequent mistakes

  • Ignoring skewness and kurtosis when a few extreme values drive the result.
  • Comparing covariances between fields measured in different units.
  • Assuming that the missing setting is applied per field in the order of the list, when it is a map by name.
  • Forgetting that one mode applies to all fields.
  • Using the aggregation on fields that were mapped without doc values.
  • Treating tiny differences in the last digits as meaningful.

21Security and Privacy Considerations

Aggregated statistics look harmless, but they can reveal individuals when groups are small, and they can expose business secrets. A little design keeps them safe.

The matrix stats aggregation returns only summary numbers, so it seems safer than returning documents. But summaries computed from very few documents can reveal the underlying values, and summaries computed from sensitive fields can leak facts that the reader was never meant to learn.

RiskWhat could happenProtection
Statistics over very small groupsThe mean of one document is that document’s value, and the correlation of two documents is exactly plus or minus one, so individual values can be inferredRequire a minimum document count for every group, and hide groups below it
Repeated narrow queriesA user narrows the population step by step until only one person is left, then reads their valuesEnforce minimum group sizes, limit filter combinations, and monitor unusual query patterns
Access to sensitive fieldsUsers learn relationships involving fields they should not see, such as salary and performance ratingUse field level security, and allow only approved fields in the analysis
Access to sensitive documentsStatistics include documents that a user should not seeRely on document level security, which applies to aggregations as well as to searches
Different views for different usersTwo users get different numbers, and someone gets confused or draws conflicting conclusionsDocument that results depend on permissions, and share results with their context
Expensive requestsA user or a bug runs many heavy aggregations and exhausts the clusterRate limits at the gateway, caps on the number of fields and buckets, and timeouts
Results copied elsewhereExported tables and screenshots outlive the access rulesControl exports, and set retention rules for shared reports
Sensitive queries in logsSlow logs and audit trails record the fields and filters that were analyzedRestrict log access, and set short retention
Everyday Analogy

A school publishes the average test score of each class, which seems harmless. But in a class with only one student, the average is that student’s score, and everyone can read it. The school therefore refuses to publish averages for classes below a minimum size. Minimum group sizes for aggregations follow the same rule.

Access control applies to aggregations

Elasticsearch checks the privileges of the caller on every request, and its document level and field level security are applied to aggregations. A user restricted to some documents gets statistics computed only over those documents. A field that a user may not read behaves as if it were not mapped for that user, so it cannot be used in the aggregation. Use dedicated roles for analysts with the least access that their work needs.

An application layer as a gatekeeper

In many designs, users do not send free-form aggregation requests to the cluster. An application service accepts a limited set of choices, builds the request itself, and returns the result. This lets you enforce an allowed list of fields, a minimum group size, a maximum number of fields, and a maximum time range, before the cluster is ever involved. It also allows you to rate limit, log, and audit the analysis.

Sensitive relationships are sensitive facts

Even without individual values, a relationship can be confidential: the link between price and discount for a customer group, or between a manager’s approvals and a metric. Treat correlation tables that involve sensitive fields with the same care as the fields themselves.

!
Compliance reminder

If your data includes personal information, summaries computed over small groups may still count as personal data. Confirm with your security and legal teams what minimum group sizes and access controls your rules require.

22Monitoring, Logging, and Metrics

Statistical requests can fail quietly, returning plausible numbers from the wrong documents. A few checks keep both the cluster and the analysis honest.

QuestionWhere to lookWhat healthy looks like
How long do the requests take?The reported time in each response, tracked by request typeStable, and consistent with the number of fields and documents
Did all shards answer?The shard failure and timed-out flags in the responseNo failures and no timeouts, because a missing shard changes the statistics
Were enough documents used?The document count in the response, compared with the matching countClose to the matching count, and above a minimum
Are heavy requests visible?The search slow log, which records the request bodyFew entries, and none from routine dashboards
Are memory protections tripping?Circuit breaker statistics on the nodesZero trips from aggregations
Is the search pool saturated?Thread pool statistics for search, including queue size and rejectionsSmall queues and no rejections
Does the data still look the same?Regular checks of the share of missing values and the count of documents per dayStable share, no sudden gaps
Are the relationships stable?Tracking key correlations over timeSlow, explainable changes
Does the aggregation still compute correctly?A canary request over a small fixed test index with known answersExactly the expected numbers, within rounding
Everyday Analogy

A laboratory that measures samples runs a known reference sample every morning. If the instrument reports the wrong value for the reference, the lab knows that something is off before it measures anything important. A canary request over a fixed test index is the reference sample for your statistics.

Partial results are the quiet danger

If a shard fails or times out, Elasticsearch may still return results from the shards that did answer, and it flags the failure in the response. For an ordinary search, missing a few hits is often tolerable. For statistics, missing a shard changes every number, in unknown directions. Make your code check the failure flags, and treat partial results as failures for anything that will be reported.

Metrics worth charting

  • Response time by number of fields. Shows the growth and lets you set limits.
  • Document count against matching count. Shows how much data is skipped.
  • Partial and timed-out responses. Show reliability.
  • Key correlations over time. Show drift in the behavior of your system or business.
  • Share of missing values per field. Shows data quality trends.
  • Search rejections and queue sizes. Show cluster pressure.

Alerts that help

Create a short list of alerts. First, an alert when a scheduled analysis returns partial results. Second, an alert when the document count falls far below its usual level. Third, an alert when the canary request returns unexpected numbers. Fourth, an alert when a monitored correlation changes by more than a set amount within a day. Fifth, an alert when search rejections rise. Each alert should link to a short runbook.

i
Log the context with every result

Store the query, fields, settings, document count, and time next to any result that you save or report. When a number is questioned later, you can reproduce it exactly.

23Failure Scenarios and Recovery

Statistical requests fail in two ways: loudly, with an error, and quietly, with a plausible but wrong answer. The quiet failures are the ones to fear.

flowchart TD
    A["A matrix stats result arrives"] --> B{"Any shard failures or timeout flags?"}
    B -->|Yes| C["Treat the result as unreliable: retry, and investigate the failing shards"]
    B -->|No| D{"Document count close to the matching count?"}
    D -->|No| E["Find out which fields are missing, and decide whether to filter or fill in"]
    D -->|Yes| F{"Any null or not-a-number values?"}
    F -->|Yes| G["Check for constant fields and tiny groups"]
    F -->|No| H["Read the shapes and correlations, and apply the checklist of traps"]
Figure 6: A short checklist to run on every result before believing it.

Scenario: a field is not numeric or not mapped

If you list a text field, or a field that does not exist, the request may fail with an error about the field type, or the field may be treated as missing so that no documents qualify. Check the mapping of every listed field, and confirm that it is a numeric type with doc values.

Scenario: the aggregation type is unknown

If the request fails because the aggregation type is not recognized, the matrix stats module may not be installed in that build. Use the standard distribution, or install the module as your deployment allows, and confirm on all nodes.

Scenario: mapping conflicts across indices

When one field is numeric in some indices and text in others, a search across all of them can fail or skip documents. Restrict the request to indices with consistent mappings, or fix the mappings by reindexing.

Scenario: partial results from failed shards

A shard that is unavailable or too slow leaves out its documents. The statistics then describe only the others, silently. Check the shard failure count in every response. Retry once, and if the failure persists, do not publish the result.

Scenario: too few documents after filtering

A narrow filter, or missing values in one field, can reduce the document count to a handful. Correlations from such a sample are unstable, and shape statistics are meaningless. Set a minimum count in your code, and report “not enough data” instead of a number.

Scenario: null or not-a-number values

A field that is constant in the selected population has zero variance, so its correlations cannot be computed. This is common in narrow groups. Treat these entries as unavailable, and do not replace them with zero.

Everyday Analogy

A pilot runs a checklist before every flight, not because the plane usually fails, but because a missed item can be costly. The checks on a statistical result, shard flags, counts, and null values, take seconds and catch the failures that would otherwise travel into reports and decisions.

Scenario: too many buckets

Nesting the aggregation inside a fine-grained grouping can hit the limit on the number of buckets in a response. The request fails with an error about too many buckets. Coarsen the grouping, use a minimum document count, or page through groups with a composite aggregation.

Scenario: the numbers changed and nobody knows why

If a correlation suddenly changes, first check whether the population changed: a new data source, a change in how a field is filled, a reindex, or a change in the time range. Compare the document counts and the share of missing values before and after. Most surprising changes come from the data, not from the aggregation.

Habits that make recovery easier

  • A checklist of checks, run automatically in the code that consumes results.
  • A canary request with known answers.
  • Saved query context with every result.
  • Minimum counts and clear “not enough data” answers.
  • A runbook for partial results and mapping conflicts.
!
Never replace missing results with zeros

A zero correlation is a real finding: no straight-line relationship. A missing correlation is a lack of information. Confusing the two leads to wrong reports and wrong decisions.

24Troubleshooting Common Problems

When something looks wrong, match the message or symptom to its likely meaning. This table covers what people meet most often.

What you seeMost likely meaningFirst things to check
An error that the aggregation type is unknownThe matrix stats module is not available in this buildDistribution type, installed modules, and node versions
An error that a field is not numeric or cannot be aggregatedA text, keyword, date, or other unsupported type was listedField mapping, and convert to a numeric field if needed
Empty results or a document count of zeroNo document has all listed fields, or the query matches nothingField names, mappings, the query, and missing values
Document count far below the matching countDocuments lacking a listed field were skippedMissing-value share per field, and the missing setting
Null or not-a-number in variance or correlationA constant field, or fewer than two documentsPopulation size and field variation after filtering
Correlations exactly plus or minus oneOnly two documents, or a perfectly linear relationship, such as a field and its own multipleDocument count, and whether one field is derived from another
Correlation slightly above one or below minus oneFloating point roundingTreat as one or minus one
Results differ slightly between identical runsFloating point addition in a different orderCompare with a small tolerance
Variance differs slightly from extended statsSample form versus population formFactor of count over count minus one
An error about too many bucketsNesting inside a very fine groupingCoarsen the grouping, use a minimum document count, or a composite aggregation
The request is very slowToo many fields, too many documents, or a cold cacheField count, query range, and repeat timings
Different users see different numbersDocument level or field level securityRoles of the users, and the documents visible to each
Numbers look plausible but disagree with a colleagueDifferent populations, modes, or missing settingsQuery, mode, missing values, time range, and data version

A calm way to debug

1

Shrink the problem

Run the aggregation with two fields on a small, filtered population, where you can check the numbers by hand.

2

Check the flags and counts

Look at shard failures, timeouts, the document count, and the matching count.

3

Check the fields

Confirm the type, doc values, units, and the share of missing values for each field.

4

Cross-check with another aggregation

Compare the mean and variance with the average and extended stats of the same field over the same documents.

5

Widen step by step

Add fields and documents gradually, and note where the numbers change or the time jumps.

6

Record the finding

Write down the symptom and the cause in your runbook so that the next person finds it in minutes.

i
A quick self-test

Create a test index with the five documents from Chapter 9, run the aggregation, and compare with the tables. If the numbers match, your setup is sound, and any surprise on real data comes from the data, not from the tool.

25From Numbers to Decisions: Presenting Results

The aggregation returns numbers. Turning them into a clear message for other people takes a few more steps, and each step protects readers from misunderstanding.

1

Write the question first

State in one sentence what you want to know, for example whether price and rating move together for products in stock this quarter.

2

Define the population

Choose the query that selects exactly the documents that the question is about, and write it down.

3

Choose the fields and the settings

List the fields, decide the mode and the treatment of missing values, and record why.

4

Run and check the counts

Compare the document count with the matching count, and check the shard flags.

5

Read the shapes

Look at skewness and kurtosis to judge whether a few extreme values could dominate.

6

Read the correlations

Sort the pairs by the size of the correlation, and note the strongest positive and negative ones.

7

Test the groups

Repeat inside the main groups, and look for differences and reversals.

8

Confirm on other data

Check the finding on another time period or a separate sample.

9

Write the message with its caveats

Say what you found, what population it applies to, how many documents it is based on, and what it does not prove.

Everyday Analogy

A weather forecaster does not just read out a number. She says where the forecast applies, how confident she is, and what could change it. A statistical finding deserves the same care: a number alone is easy to misread, and a number with its context is a message that people can use.

A friendly layout for the correlation table

Show the correlations as a square table with the fields on both axes, round to two decimals, and shade the cells by strength and sign, for example warm colors for positive values and cool colors for negative ones. Show the document count above the table. Because the table is symmetric, you can hide the upper half to reduce clutter. Sorting the list of pairs by the absolute value of the correlation gives a quick ranking of the most interesting relationships.

Element of a good reportWhy it matters
The population and the time rangeThe same fields can behave differently in another population
The document count and the skipped shareShows how solid and how complete the sample is
The correlation table, roundedThe main result, without false precision
Words for strength, such as weak, moderate, strongHelps non-specialists read the numbers
A group breakdown for the main groupsGuards against Simpson’s paradox
A statement of what the analysis does not showPrevents readers from inferring causes
The date and the data versionAllows the result to be reproduced and updated

Pairing numbers with pictures

A correlation coefficient summarizes a relationship in one number, but a picture shows whether that number is a fair summary. A scatter plot of a sample of the documents reveals outliers, curves, and clusters that the number hides. A good practice is to use the aggregation to find the interesting pairs and then fetch a modest random sample of documents for those pairs to draw the scatter plots.

What about Kibana?

Kibana’s built-in visual editors are designed around the common aggregations, and, in many versions, they do not offer matrix stats as a ready-made choice. You can still run the aggregation from the developer console, from your own application, or from scheduled jobs, and display the results in a custom table or chart. Another approach is to precompute the statistics into a small summary index with a transform, and then build ordinary charts on that index. Check your version for what is available.

Alerting on drift

Because the relationship between metrics reflects how a system behaves, a change in correlation can be an early signal of a change in the system. Schedule the aggregation over fixed windows, store the correlations, and alert when a key value moves outside its normal band. Combine this with the checks on counts and partial results so that alerts are based on reliable numbers.

Keep the language honest

  • Say “tends to rise together” instead of “causes.”
  • Say “in this population and period” instead of “in general.”
  • Say “based on N documents” so that readers can judge the sample.
  • Say “straight-line relationship” when you mean the Pearson correlation.
i
Make the caveat part of the template

Build the population, the count, and the “what this does not show” line into every report template. When the caveat is always on the page, it is far less likely to be dropped when the finding travels.

26Real-World Scenarios

Here are four common situations, with rough numbers, showing the aggregation at work. The companies are imaginary, and all figures are invented to show the shape of the effect.

Scenario 1: The store that almost believed a false pattern

PriceBloom, an imaginary retailer, runs the aggregation on price, rating, and units sold across its catalog. The overall correlation between price and rating is moderately positive, and a manager suggests raising prices to improve ratings. The analyst nests the aggregation inside a terms aggregation by category and finds that inside most categories, the relationship is weak or slightly negative. Categories with higher prices simply have more demanding products and more enthusiastic buyers. The price increase idea is dropped before it costs anything.

Scenario 2: The utility that screened sensors

GridGuard, an imaginary power utility, records dozens of sensor readings for each transformer, plus a numeric health score. Engineers run the aggregation in batches of six fields, always including the health score, over the last quarter. Two readings, oil temperature and vibration, stand out with moderately strong negative correlations with health. The team exports samples for these two, draws scatter plots, and finds that a handful of transformers with extreme vibration drive most of the effect. They inspect those units first, rather than adjusting fleet-wide rules.

Scenario 3: The marketing team and the shared trend

AdAtlas, an imaginary agency, sees a correlation of about 0.95 between weekly advertising spend and weekly revenue and celebrates. A colleague points out that both numbers have grown steadily for a year. The team recomputes using the week-to-week changes instead of the levels, and the correlation falls to about 0.2. The growth in both came mainly from the season and the size of the business. They redesign their tests around controlled experiments.

Scenario 4: The operations team and the daily correlation chart

NetNimbus, an imaginary cloud service, computes the daily correlation between request rate, CPU load, and response time for each service, using a date histogram and a nested aggregation, stored by a scheduled transform. After a release, the correlation between CPU load and response time for one service jumps from about 0.3 to about 0.8 and stays there. The team investigates and finds a new code path that blocks under load. The change in correlation reached their dashboard days before any customer complaint arrived.

A worked example with numbers

1

Set the scene

An analyst studies price and rating over products sold this quarter. The query matches 1,000,000 documents. These figures are invented for illustration.

2

Check the count

The response reports a document count of 940,000. So 60,000 documents, six percent, lack a rating and were skipped. The analyst notes that unrated products are mostly new, so the result describes established products.

3

Check the shapes

The price field has a skewness of about 3.1, a long tail of expensive items. The rating field has a skewness near minus 0.9, since most ratings are high. The price correlation may be dominated by a few very expensive items.

4

Read the correlation

The correlation between price and rating is about 0.12, a weak positive relationship.

5

Transform and repeat

Using the logarithm of the price, the skewness falls to about 0.4, and the correlation rises to about 0.31. The relationship was masked by the extreme prices.

6

Check the groups

By category, the correlation ranges from minus 0.05 to 0.45, with most categories between 0.2 and 0.4. The relationship holds inside groups, not only overall.

7

Write the message

Among rated products this quarter, higher-priced items tend to have somewhat higher ratings, in a weak to moderate way that holds inside most categories. The result does not show that price causes ratings.

27Frequently Asked Questions

Q1What is a matrix stats aggregation in Elasticsearch?
It is a metric aggregation that computes statistics for several numeric fields at once: count, mean, variance, skewness, and kurtosis for each field, and covariance and correlation for every pair of fields. The pairwise results form a matrix.
Q2Which statistics does it not provide?
It does not report minimum, maximum, sum, standard deviation, or percentiles. Use stats, extended stats, or percentiles on single fields for those. You can take the square root of the variance to get the standard deviation.
Q3Is the result exact or approximate?
It is exact, apart from tiny floating point rounding differences. Each shard keeps small running totals, and the coordinating node merges them without approximation.
Q4What happens to documents that are missing one of the fields?
By default they are skipped for the whole calculation. You can supply default values per field with the missing setting, but that can distort the results, so use it only when the default is truthful.
Q5How does it handle fields with several values?
The mode setting reduces the values of each document to one number. The options are average, which is the default, minimum, maximum, sum, and median. The same mode applies to all listed fields.
Q6What kinds of fields can I use?
Numeric fields with doc values. Text and keyword fields are not accepted, and dates and booleans usually need to be stored as numbers first. Do not use numeric identifiers, which are labels rather than measures.
Q7Why is it slow with many fields?
Every pair of fields needs its own running totals, and the number of pairs grows with the square of the number of fields. Use fewer fields and a narrower query.
Q8Does a high correlation mean that one thing causes the other?
No. Correlation shows that two fields move together in a straight-line pattern in the selected documents. It can come from a shared cause, a common trend, hidden groups, outliers, or chance.
Q9Can I use it inside groups?
Yes. Nesting it inside a terms, date histogram, or filters aggregation gives separate statistics for each group, which is very useful for spotting differences and reversals such as Simpson’s paradox.
Q10What does a correlation of zero mean?
It means that there is no straight-line relationship in the selected documents. There may still be a curved relationship, such as one field being the square of another.
Q11Why do I see null values in the response?
Some statistics are undefined for tiny samples or constant fields. With fewer than two documents, the variance cannot be computed, and a field that never varies has no correlations. Treat nulls as missing information, not as zeros.
Q12Why does the variance differ slightly from extended stats?
Matrix stats reports the sample variance, dividing by the count minus one, while extended stats commonly reports the population form by default. The two differ by a factor of the count over the count minus one, which is tiny for large counts.
Q13Can it leak private information?
Yes, when groups are very small, since the mean of one document is its value. Enforce minimum group sizes, use field and document level security, and control who can run free-form analyses.
Q14Is it available in every version?
It has been available since Elasticsearch 5.0 as the matrix stats module, and it is included in standard distributions. Details of parameters and defaults should be confirmed in the documentation for the version you run.

28Summary and Key Takeaways

The matrix stats aggregation is a simple idea with a useful payoff: one request, exact statistics, and a table of how your numeric fields move together. Here is everything to remember.

Key Takeaways

  • What it is: a metric aggregation that reports count, mean, variance, skewness, and kurtosis for each of several numeric fields, plus covariance and correlation for every pair.
  • How it works: each shard keeps small running totals while reading doc values, the coordinating node merges them exactly, and only a tiny table travels back to the client.
  • What it needs: numeric fields with doc values, a clear population chosen by a query, and a decision about multi-valued fields and missing values.
  • What it costs: reading every matching document once, with work that grows with the square of the number of fields, so keep the field list short and the query narrow.
  • How to read it: check the document count first, then the shape statistics, then the correlations, and always compare the overall result with the results inside groups.
  • What it cannot tell you: it shows straight-line association only, not causes, curves, or significance, and it can be misled by outliers, trends, and hidden groups.
  • How to run it safely: guard against small groups and sensitive fields, check shard failures on every result, monitor drift with canary requests, and report findings with their population, count, and caveats.

Keep in mind that parameters, defaults, supported field types, and the availability of related features can change between Elasticsearch versions, so confirm exact details against the documentation of the release you run. With that habit, and the ideas in this guide, you can use the aggregation as a fast, exact first look at how your numbers relate, and pair it with the right care to turn those numbers into decisions you can trust.