如何将Elasticsearch查询转换为聚合Builder
我正在尝试使用Elasticsearch编写查询,其中响应应为具有其他字段条件的列的总和。我能够使用Elasticsearch查询来完成此操作,但无法做到的是在Elasticsearch API中使用Elasticsearch gentregationBuilder。有人请帮助我在Elasticsearch API中编写代码,如以下附加查询吗?
{
"query": {
"bool": {
"must": [
{
"match": {
"customerId": "13b7e2e8-8bf0-435b-b7f7-949c2e69b1d7"
}
}
],
"must_not": [
{
"match": {
"state": "Cancelled"
}
}
],
"should": []
}
},
"aggs": {
"totalStakes": {
"sum": {
"field": "totalStake"
}
}
}
}
我已经尝试了以下代码,但没有预期的工作。
AggregationBuilder sumOfTotalStake = AggregationBuilders.sum("totalStake").field("totalStake");
BoolQueryBuilder bqb = boolQuery().mustNot(termQuery("state", "Cancelled").must(termQuery("customerId", "13b7e2e8-8bf0-435b-b7f7-949c2e69b1d7")));
// create the filter aggregation and add the sub-aggregation
FilterAggregationBuilder aggregation = AggregationBuilders.filter("totalStakes", bqb)
.subAggregation(sumOfTotalStake);
预期结果应低于格式:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 4.3412046,
"hits": []
},
"aggregations": {
"totalStakes": {
"value": 65579
}
}
}
I am trying to write a query using elasticsearch where response should be sum of a column with condition of other fields. I'm able to do it using elasticsearch query but unable to do is using elasticsearch aggregationbuilder in elasticsearch api. Anyone please help me to write the code in elasticsearch api same like below attached query?
{
"query": {
"bool": {
"must": [
{
"match": {
"customerId": "13b7e2e8-8bf0-435b-b7f7-949c2e69b1d7"
}
}
],
"must_not": [
{
"match": {
"state": "Cancelled"
}
}
],
"should": []
}
},
"aggs": {
"totalStakes": {
"sum": {
"field": "totalStake"
}
}
}
}
I have tried the below code but it's not working as expected.
AggregationBuilder sumOfTotalStake = AggregationBuilders.sum("totalStake").field("totalStake");
BoolQueryBuilder bqb = boolQuery().mustNot(termQuery("state", "Cancelled").must(termQuery("customerId", "13b7e2e8-8bf0-435b-b7f7-949c2e69b1d7")));
// create the filter aggregation and add the sub-aggregation
FilterAggregationBuilder aggregation = AggregationBuilders.filter("totalStakes", bqb)
.subAggregation(sumOfTotalStake);
Expected result sould be below format :
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 4.3412046,
"hits": []
},
"aggregations": {
"totalStakes": {
"value": 65579
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在Java中使用以下代码。该代码在ES 7.X版本中,但相同或使用较小的更改将起作用。
更新:
您可以设置
size
param to0
获得预期结果。您可以保持上述代码,并且它将仅返回聚合输出。You can use below code in java. This code is in ES 7.X version but same or with minor change it will work.
Updated:
you can set
size
param to0
for getting your expected result. You can keep above code as it and it will return only aggregation output.