Search code examples
elasticsearch

Aggregate with query bool


I have this query that works as expected:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "valueType": {
              "value": "VARIABLE",
              "boost": 1
            }
          }
        },
        {
          "term": {
            "intent": {
              "value": "CREATED",
              "boost": 1
            }
          }
        },
        {
          "term": {
            "value.name": {
              "value": "item",
              "boost": 1
            }
          }
        },
        {
          "term": {
            "recordType": {
              "value": "EVENT",
              "boost": 1
            }
          }
        },
        {
          "query_string": {
            "query": "*\\\"N_POLIZZA\\\"\\:\\\"2264798\\\"*",
            "fields": [
              "value.value"
            ]
          }
        }
      ]
    }
  },
  "size": 10,
  "from": 0,
  "_source": true
}

Here the mapping:

enter image description here

What I'm trying to do is to aggregate (group by) by processInstanceKey, so I add this after query {}:

{
  "query": {
    "bool": {
      ...
    }
  },
  "aggs": {
    "groupby_processInstanceKey": {
      "terms": {
        "field": "value.processInstanceKey"
      }
    }
  },
  "size": 10,
  "from": 0,
  "_source": true
}

But it does not work, results are still the same, it seems like no aggregation has been done. I'm a newbie and probably miss something.


Solution

  • The aggregations results come after the hits, you need to scroll to the bottom in order to see the aggregation results.

    If you're not interested in hits, you can also set "size": 0 so you only get aggregation results.

    UPDATE:

    If you want to paginate the your buckets, you need to use the composite aggregation with a terms source instead.

    GET /_search
    {
      "query": {
        "bool": {
          ...
        }
      },
      "aggs": {
        "my_buckets": {
          "composite": {
            "size": 10,
            "sources": [
              { 
                 "groupby_processInstanceKey": { 
                    "terms": { 
                       "field": "value.processInstanceKey",
                       "order": "asc"
                    }
                 } 
              }
            ]
          }
        }
      }
    }