Search code examples
elasticsearchmappingaggregationbucket

ElasticSearch dynamic bucket aggregations


Currently I have the following mapping:

    array(
        'index' => 'my_index',
        'body'  => array(
            'mappings' => array(
                'products' => array(
                    '_source'    => array('enabled' => false),
                    'properties' => array(
                        'id'     => array('type' => 'integer'),
                        'active' => array('type' => 'boolean'),
                        'specs'  => array(
                            'type'       => 'nested',
                            'properties' => array(
                                'id'      => array('type' => 'integer'),
                                'value'   => array('type' => 'text'),
                                'visible' => array('type' => 'boolean')
                            )
                        )
                    )
                )
            )
        )
    );

I would like to query the products. And have ElasticSearch return the specifications aggregated. But for each specs.id a bucket with all the values. And only if visible is true.

  "aggregations": {
      "specs_2": {
        "buckets": [
          {
            "key": "Yes",
            "doc_count": 90
          },
          {
            "key": "No",
            "doc_count": 80
          },
        ]
      },
      "specs_4": {
        "buckets": [
          {
            "key": "Yes",
            "doc_count": 190
          },
          {
            "key": "No",
            "doc_count": 180
          },
        ]
      }
  }

Without knowing the specification ids that are in the data set.

Is this possible?


Solution

  • Have you tried doing a nested term aggregation on path specs and field properties.id ? This should create buckets with different ids and specs docs having same id will fall in same buckets. Doing a filter aggregation on visibility will filter out all docs with visibility false. Now you can do a term aggregation on value as sub-aggregation of filter aggregation to get the desired output.