Browse Source

ESQL: Document the pattern to count TRUE (#110820)

This adds an example to the docs an example of counting the TRUE results
of an expression. You do `COUNT(a > 0 OR NULL)`. That turns the `FALSE`
into `NULL`. Which you need to do because `COUNT(false)` is `1` -
because it's a value. But `COUNT(null)` is `0` - because it's the
absence of values.

We could like to make something more intuitive for this one day. But for
now, this is what works.
Nik Everett 1 year ago
parent
commit
9f001169c6

+ 25 - 0
docs/reference/esql/functions/count.asciidoc

@@ -56,3 +56,28 @@ include::{esql-specs}/stats.csv-spec[tag=docsCountWithExpression]
 |===
 include::{esql-specs}/stats.csv-spec[tag=docsCountWithExpression-result]
 |===
+
+[[esql-agg-count-or-null]]
+To count the number of times an expression returns `TRUE` use
+a <<esql-where>> command to remove rows that shouldn't be included:
+
+[source.merge.styled,esql]
+----
+include::{esql-specs}/stats.csv-spec[tag=count-where]
+----
+[%header.monospaced.styled,format=dsv,separator=|]
+|===
+include::{esql-specs}/stats.csv-spec[tag=count-where-result]
+|===
+
+To count the same stream of data based on two different expressions
+use the pattern `COUNT(<expression> OR NULL)`:
+
+[source.merge.styled,esql]
+----
+include::{esql-specs}/stats.csv-spec[tag=count-or-null]
+----
+[%header.monospaced.styled,format=dsv,separator=|]
+|===
+include::{esql-specs}/stats.csv-spec[tag=count-or-null-result]
+|===

+ 28 - 0
x-pack/plugin/esql/qa/testFixtures/src/main/resources/stats.csv-spec

@@ -1158,6 +1158,34 @@ word_count:long
 // end::docsCountWithExpression-result[]
 ;
 
+count_or_null
+// tag::count-where[]
+ROW n=1
+| WHERE n < 0
+| STATS COUNT(n)
+// end::count-where[]
+;
+
+// tag::count-where-result[]
+COUNT(n):long
+            0
+// end::count-where-result[]
+;
+
+
+count_or_null
+// tag::count-or-null[]
+ROW n=1
+| STATS COUNT(n > 0 OR NULL), COUNT(n < 0 OR NULL)
+// end::count-or-null[]
+;
+
+// tag::count-or-null-result[]
+COUNT(n > 0 OR NULL):long | COUNT(n < 0 OR NULL):long
+                        1 | 0
+// end::count-or-null-result[]
+;
+
 countMultiValuesRow
 ROW keyword_field = ["foo", "bar"], int_field = [1, 2, 3] | STATS ck = COUNT(keyword_field), ci = COUNT(int_field), c = COUNT(*);