嵌套类型属性上的聚合 - 使用NEST

时间:2015-06-26 18:36:04

标签: elasticsearch nest

我正在尝试聚合嵌套类型的计数或嵌套类型的属性总和,但无法让NEST在计算中包含多个嵌套文档。

        var result = elasticClient.Search<ItemIncidents>(s => s
             .Aggregations(a => a
             .Terms("group by role", ts => ts
                 .Field(o => o.LabelName)
                 .d
                 .Aggregations(aa => aa
                     .Sum("sum incidents", sa => sa                           
                          .Field("incidents.index")))
                 )
             )
        );

使用的类是:

public class ItemIncidents
{
    public int Id{get;set;}
    public string LabelName { get; set; }

  //  [ElasticProperty(Type = FieldType.Nested)]
    public List<IncidentInstance> Incidents { get; set; }
}

 public partial class IncidentInstance:     {
    public string Id { get; set; }
    public int Index { get; set; }
    public int Count { get; set; }
  }

如果每个ItemIncident有多个eventsinstance,则弹性只计算列表中聚合计数的最后一个。如果所有IncidentInstances的Index = 3的值,并且有五个文档,每个都有两个事件实例,我得到的结果是15(5 * 1 * 3),而不是30(5 * 2 * 3)。 / p>

这是我需要在Index字段上做一些特殊属性映射的问题吗?

1 个答案:

答案 0 :(得分:0)

您可以将nested aggregation用于嵌套类型。

所以,对于你的文件:

public class ItemIncidents
{
    public int Id { get; set; }
    public string LabelName { get; set; }

    [ElasticProperty(Type = FieldType.Nested)]
    public List<IncidentInstance> Incidents { get; set; }
}

public class IncidentInstance
{
    public string Id { get; set; }
    public int Index { get; set; }
    public int Count { get; set; }
}

使用聚合

var searchResponse = client.Search<ItemIncidents>(s => s.Aggregations(a => a
    .Nested("indexCount", nested => nested
        .Path(p => p.Incidents)
        .Aggregations(aa => aa.Sum("sum", sum => sum.Field(f => f.Incidents.First().Index))))));