简体   繁体   中英

Elasticsearch - Count how many records have specific field values, for multiple fields

I have an elasticsearch index containing documents like this:

{"id": 1, "red": true, "green": true, "blue": true }
{"id": 2, "red": false, "green": false, "blue": true }
{"id": 3, "red": false, "green": true }
{"id": 4, "red": true, "green": true, "blue": false }

For each of the color attributes, I want to count how many true I have. New colors may appear anytime. Essentially, I need that output, in some form or another:

red: 2
green: 3
blue: 2

How can I get that in one query, ideally with a DSL or SQL query?

Bonus points if I can turn that into a data transform / rollup per day.

you can use Bucket aggregations

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html

smth like that:

GET /my-index-000001/_search

{
"aggs": {
    "red": {
      "terms": {
        "field": "red"
      }
    },
    "green": {
      "terms": {
        "field": "green"
      }
    },
    "blue":{ 
      "terms": {
        "field": "green"
      }
    }
  }
}

It can also be done with SQL, with something like this:

select sum(red::int) as red
     , sum(green::int) as green
     , sum(blue::int) as blue
from my_index

Not entirely sure how the NULLs are handled in this case (not tested), but it works at least with non-null values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM