eugene
eugene

Reputation: 41685

Elasticsearch, composite and sub(?) aggregations

I'm using composite to scroll through whole data. (it's like pagination)

Suppose a car selling data,

For each day, I'd like to count the number of cars sold per car-brand

{
  day1: {
    honda: 3,
    bmw: 5
  },
  day2: {
    honda: 4,
    audi: 1,
    tesla:5
  }
}

I'm doing something like the following but it doesn't work

GET _search
{
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          {
            "date": {
              "date_histogram": {
                "field": "created_at",
                "calendar_interval": "1d"
              },
              "aggs": {
                "car_brand": {
                  "terms": {
                    "field": "car_brands"
                  }
                }
              }
            }
          }
        ]
      }
    }
  }
}

with error message

{
  "error" : {
    "root_cause" : [
      {
        "type" : "x_content_parse_exception",
        "reason" : "[14:17] [composite] failed to parse field [sources]"
      }
    ],
    "type" : "x_content_parse_exception",
    "reason" : "[14:17] [composite] failed to parse field [sources]",
    "caused_by" : {
      "type" : "illegal_state_exception",
      "reason" : "expected value but got [FIELD_NAME]"
    }
  },
  "status" : 400
}

Upvotes: 0

Views: 1225

Answers (2)

Jiří Chmiel
Jiří Chmiel

Reputation: 876

Try this

GET _search
{
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          {
            "date": {
              "date_histogram": {
                "field": "created_at",
                "calendar_interval": "1d"
              }
            }
          }
        ]
      },
      "aggs": {
         "car_brand": {
            "terms": {
              "field": "car_brands"
            }
         }
      }
    }
  }
}

https://github.com/elastic/elasticsearch/edit/8.10/docs/reference/aggregations/bucket/composite-aggregation.asciidoc

Upvotes: 0

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

Composite aggs cannot directly accept sub-aggs. Go with

GET _search
{
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          {
            "date": {
              "date_histogram": {
                "field": "created_at",
                "calendar_interval": "1d"
              }
            }
          },
          {
            "car_brand": {
              "terms": {
                "field": "car_brands"
              }
            }
          }
        ]
      }
    }
  }
}

instead.

Upvotes: 1

Related Questions