聚合按日期排序的ElasticSearch字段

时间:2018-09-20 13:31:41

标签: .net elasticsearch nest

我的索引中存储了文档,我想将所有文档与一个键进行汇总,并针对每个按降序排序的汇总结果,获取最后一个文档的特定字段。

我的映射如下:

    {
     "mapping": {
        "campaignbudgetrecord": {
            "properties": {
                "campaignBudget": {
                "type": "nested",
                "properties": {
                    "accountId": {
                    "type": "integer"
                    },
                    "advertiserId": {
                    "type": "integer"
                    },
                    "budget": {
                    "type": "double"
                    },
                    "budgetType": {
                    "type": "integer"
                    },
                    "campaignId": {
                    "type": "integer"
                    },
                    "paid": {
                    "type": "double"
                    },
                    "paidDaily": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                        }
                    }
                    },
                    "paidToday": {
                    "type": "double"
                    },
                    "totalBudget": {
                    "type": "double"
                    }
                }
                },
                "campaignBudgetDate": {
                "type": "date"
                }
            }
        }
    }
}

总而言之,我想按键(accountId)汇总我的所有CampaignBudgetRecords,按CampaignBudgetDate排序,并对每个最后一个条目的totalBudget求和,以便从其广告系列中获得我的Account实体的总预算。

我尝试使用以下方法做到这一点:

var accountBudgetResponse = await elasticClient.SearchAsync<CampaignBudgetRecord>(s =>
    s.Index(_variableService.ElasticSearchCampaignBudgetIndexName).Type(typeof(CampaignBudgetRecord))
        .Aggregations(a => a.Nested("Budget", n => n.Path(p => p.CampaignBudget)
            .Aggregations(ag => ag
                .Terms("ByCampaignId", tad => tad
                    .Field(o => o.CampaignBudget.CampaignId)))
            .Aggregations(ad => ad
                .Terms("CampaignTotalBudget", sad => sad
                    .Field(o => o.CampaignBudget.TotalBudget)
                ))
            .Aggregations(ad => ad
                .Sum("AccountTotalBudget", sad => sad
                    .Field(o => o.CampaignBudget.TotalBudget)
                )))).Sort(ss => ss.Field(f => f.Field(ff => ff.CampaignBudgetDate).Order(SortOrder.Descending))).Query(q => q.Nested(n =>
            n.Path(p => p.CampaignBudget).Query(qq => qq.Bool(b =>
                b.Must(m => m.Match(a =>
                    a.Field(f => f.CampaignBudget.AccountId).Query(visualizationEntity.EntityId.ToString()))))))).Size(0));

但是我检索了一个带有全部totalBudget之和的桶,即使是那些来自同一campaignBudget campaignId的桶,因此它也不会汇总每个campaignBudget的最后一个桶。 我已经阅读了NEST.NET文档中的一些示例,但没有设法使其正常运行,我很困惑。

0 个答案:

没有答案