Restrict ElasticSearch aggregation by type?

2019-06-22 06:30发布

How do you perform an ElasticSearch aggregation for a specific type? I realize that you can specify the index and/or type in the request Url, but I want to perform aggregations on two distinct types.

Thank you!

2条回答
一纸荒年 Trace。
2楼-- · 2019-06-22 06:53

If you can aggregate by an field in all types:

curl -XGET 'localhost:9200/index/type1,type2,type3,typeN/_search/?pretty=true' -d '{
      "query": {
        "filtered": {
          "query": {
            "match_all": {}
          }
        }
      },
      "size": 0,
      "aggs": {
        "field_aggs": {
          "terms": {
            "size": 0,
            "field": "field_common_on_all_types"
          },
          "aggs": {
            "testing": {
              "terms": {
                "field": "_type"
              },
              "aggs": {
                "testing": {
                  "date_histogram": {
                    "field": "date_start",
                    "interval": "month",
                    "format": "yyyy-MM-dd HH:mm:ss"
                  }
                }
              }
            }
          }
        }
      }
    }'
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-22 07:19

You could filter the aggregation by type, and then use sub-aggregations. For example:

{
  "aggs": {
    "Test 1": {
      "filter": {
        "type": {
          "value": "type1"
        }
      },
      "aggs": {
        "agg_name": {
          "terms": {
            "field": "field1",
            "size": 10
          }
        }
      }
    },
    "Test 2": {
      "filter": {
        "type": {
          "value": "type2"
        }
      },
      "aggs": {
        "agg_name": {
          "terms": {
            "field": "field2",
            "size": 10
          }
        }
      }
    }
  }
}
查看更多
登录 后发表回答