如何在弹性中嵌入2个以上的聚合?

时间:2016-03-04 16:59:44

标签: elasticsearch

我正在创建一个允许用户创建客户数据报告的应用程序,用户可以添加0个或更多分组字段。

我正在使用弹性2.2.0,所以如果用户想要按天分组,那么按年龄然后按性别分组,程序会将以下查询发送到弹性:

{
  "aggs": {
    "group_a": {
      "date_histogram": {
        "field": "transactionDate",
        "interval": "day"
      },
      "aggs": {
        "group_b": {
          "terms": {
            "field": "age"
          }
        },
        "aggs": {
          "group_c": {
            "terms": {
              "field": "sex"
            }
          }
        }
      }
    }
  }
}

我收到此错误:

{
  "error": {
    "root_cause": [
      {
        "type": "search_parse_exception",
        "reason": "Could not find aggregator type [group_c] in [aggs]",
        "line": 15,
        "col": 11
      }
    ]
  }
}

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

If you want to nest group_c into group_b, you should use this json:

{
  "aggs": {
    "group_a": {
      "date_histogram": {
        "field": "transactionDate",
        "interval": "day"
      },
      "aggs": {
        "group_b": {
          "terms": {
            "field": "age"
          },
          "aggs": {
            "group_c": {
              "terms": {
                "field": "sex"
              }
            }
          }
        }
      }
    }
  }
}

Note that you were defining group_c outside of group_b, that was the error.

答案 1 :(得分:3)

看起来你还有一个额外的aggs。请尝试删除aggs部分周围的group_c

{
  "aggs": {
    "group_a": {
      "date_histogram": {
        "field": "transactionDate",
        "interval": "day"
      },
      "aggs": {
        "group_b": {
          "terms": {
            "field": "age"
          }
        },
        "group_c": {
          "terms": {
            "field": "sex"
          }
        }
      }
    }
  }
}

这是ES documentation建议撰写查询的方式(aggregation_name_1aggregation_name_2):

"aggregations" : {
    "<aggregation_name_1>" : {
        "<aggregation_type>" : {
            <aggregation_body>
        }
        [,"meta" : {  [<meta_data_body>] } ]?
        [,"aggregations" : { [<sub_aggregation>]+ } ]?
    }
    [,"<aggregation_name_2>" : { ... } ]*
}

答案 2 :(得分:0)

请参阅我对数据所做的示例,我使用了过滤器聚合

curl -XGET "http://192.168.99.100:9200/loja/produtos/_search" -d'
{
  "aggs" : {
    "messages" : {
      "filters" : {
        "filters" : {
          "names" :   { "term" : { "nome" : "produto"   }},
          "descriptions" : { "term" : { "description" : "short" }}
        }
      },
      "aggs" : {
        "sumPeso" : {
           "sum" : {
               "field" : "peso" 
           } 
        },
        "sumValor": {
           "sum" : {
               "field" : "valor" 
           } 
        }
      }
    }
  }
}'

如果你不明白,请问我