Multiple group-by in Elasticsearch

elasticsearch, nosql-aggregation

Solution

You can do it by 2 ways :

1) using multiple fields in a single facet result :

example for single fields facet :

curl -X GET "http://localhost:9200/sales/order/_search?pretty=true" -d '{
  "query": {
    "query_string": {
      "query": "shohi*",
      "fields": [
        "billing_name"
      ]
    }
  },
  "facets": {
    "facet_result": {
      "terms": {
        "fields": [
          "status"
        ],
        "order": "term",
        "size": 15
      }
    }
  }
}'

example for multiple field in a single facet result :

curl -X GET "http://localhost:9200/sales/order/_search?pretty=true" -d '{
  "query": {
    "query_string": {
      "query": "shohi*",
      "fields": [
        "billing_name"
      ]
    }
  },
  "facets": {
    "facet_result": {
      "terms": {
        "fields": [
          "status",
          "customer_gender",
          "state"
        ],
        "order": "term",
        "size": 15
      }
    }
  }
}'

2) Use multiple facet result set :

curl -X GET "http://localhost:9200/sales/order/_search?pretty=true" -d '{
  "query": {
    "query_string": {
      "query": "*",
      "fields": [
        "increment_id"
      ]
    }
  },
  "facets": {
    "status_facets": {
      "terms": {
        "fields": [
          "status"
        ],
        "size": 50,
        "order": "term"
      }
    },
    "gender_facets": {
      "terms": {
        "fields": [
          "customer_gender"
        ]
      }
    },
    "state_facets": {
      "terms": {
        "fields": [
          "state"
        ],
        ,
        "order": "term"
      }
    }
  }
}'

Reference Link : http://www.elasticsearch.org/guide/reference/api/search/facets/terms-facet.html

Problem

I need to aggregate (group-by) using 3 fields in ES. Can I do that in 1 query or that I need to use a facet + iterate for each column? Thank you

Original source