ohadinho
ohadinho

Reputation: 7144

Aggregate by two or more fields in elasticsearch

I have many documents with various ProcessName. Each has some status code named Code.

I need to aggregate the documents by those two fields.

For instance:

ProcessA 
code: 1
count: 220 

ProcessA 
code: 2
count: 335

ProcessB
code: 2
count: 520 

ProcessC
code: 3
count: 520 

I've managed to aggregate only by one field (ProcessName):

POST /_search
{
  "query": {
        "bool": {
          "must": [
            {
              "term": {
                "_type": "monitor"
              }
            }
          ]
        }
  },
  "aggs" : {
        "ProcessNameAgg" : {
            "terms" : { "field" : "ProcessName",
                        "size" : 5,
                        "order" : { "_count" : "desc" }
            }
        }
  }
}

I've tried to make terms an array with two fields, but unfortunately I'm getting parsing exception (terms should get ONLY one field).

Upvotes: 0

Views: 29

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52366

Try this:

POST /_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "_type": "monitor"
          }
        }
      ]
    }
  },
  "aggs": {
    "ProcessNameAgg": {
      "terms": {
        "field": "ProcessName",
        "size": 5,
        "order": {
          "_count": "desc"
        }
      },
      "aggs": {
        "codes": {
          "terms": {
            "field": "code",
            "size": 10
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions