【发布时间】:2020-02-12 07:34:31
【问题描述】:
我有以下POCO
public class Collection
{
public string Amount { get; set; }
public string AccountId { get; set; }
public string ReceiptId { get; set; }
}
我在找
a) 金额总和 b) ReceiptId 计数
按 AccountId 分组使用 Nest。
由于我是 Elastic Search 和 Nest 的新手,我很难构建查询。
这是我迄今为止尝试过的
var result = ConnectionToES.EsClient().Search<Collection>(s => s
.Index("collections")
.Aggregations(a => a
.Terms("ReceiptId", ts => ts
.Field(o => o.AccountId)
.Aggregations(aa => aa.Sum("Amount", sa => sa.Field(o => Convert.ToDecimal(o.Amount)))
)
)
)
);
但是当我使用 LINQ 做同样的事情时,它可以工作
var res = ConnectionToES.EsClient().Search<Collection>(s => s
.Index("collections")
.From(0)
.Size(1000)
.Query(q => q.MatchAll()));
List<Collection> objCollection = new List<Collection>();
foreach (var hit in res.Hits)
{
objCollection.Add(
new Collection
{
Id = hit.Source.Id.ToString()
,
Amount = string.IsNullOrEmpty(hit.Source.Amount.ToString()) ? "0" : hit.Source.Amount.ToString()
,
AccountId = hit.Source.AccountId.ToString()
,
ReceiptId = hit.Source.ReceiptId.ToString()
,
CollectorId = hit.Source.CollectorId.ToString()
,
CollectionDate = hit.Source.CollectionDate.ToString()
});
}
var aggrResult = objCollection.GroupBy(t => t.AccountId)
.Select(t => new
{
AccountNumber = t.Key,
Count = t.Count(),
Amount = t.Sum(item => Convert.ToDouble(item.Amount)),
}).ToList();
我想以 ES 方式进行相同的聚合。
【问题讨论】:
-
你想要什么:.GroupBy(x => x.AccountId) .Select(x => new { id = x.AccountId, count = x.Count(), total = x.Sum( y => y.Amount)}) .ToList();
-
是的,但采用 Elastic Search /NEST 样式。先生,我想使用 NEST 在 Elastic Search 中执行聚合
-
您好,请分享es映射。请注意,es 字段区分大小写,如果您自动映射我认为 es 创建一个“receiptId”字段,而不是“ReceiptId”。此外,您还必须按如下所述更改映射,并将字段 Amount 索引为数值(聚合在 es 端进行,Convert.ToDecimal( 在您的示例中有废话)。
标签: c# elasticsearch nest