NEST - 如何进行多个嵌套聚合?

时间:2015-12-09 10:27:40

标签: elasticsearch nest elasticsearch-net

如何进行多个嵌套聚合?

我尝试过这样的事情:

Aggregations(x => x
                  .Nested("Facets", y => y.Path("categories")
                    .Aggregations(r => r.Terms("categories", w => w.Field(q => q.Categories.FirstOrDefault().Id))
                  )).Nested("Facets2", s => s.Path("brand")
                    .Aggregations(e => e.Terms("brand", w => w.Field(q => q.Brand.Id))
                  )));

但它会以Facets2

的孩子身份返回Facets

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您使用NEST客户端版本1.7.1按预期工作的聚合,如此示例所示

void Main()
{
    var settings = new ConnectionSettings();
    var connection = new InMemoryConnection(settings);
    var client = new ElasticClient(connection : connection);

    var response = client.Search<Example>(s => s
        .Aggregations(aggs => aggs
            .Nested("Facets", nested => nested
                .Path(p => p.Categories)
                .Aggregations(r => r
                    .Terms("categories", w => w
                        .Field(q => q.Categories.FirstOrDefault().Id)
                    )
                )
            )
            .Nested("Facets2", nested => nested
                .Path(p => p.Brand)
                .Aggregations(e => e
                    .Terms("brand", w => w
                        .Field(q => q.Brand.Id)
                    )
                )
            )
        )
    );

    Console.WriteLine(Encoding.UTF8.GetString(response.RequestInformation.Request));
}

public class Example
{
    public IList<Category> Categories { get; set; }
    public Brand Brand { get; set; }
}

public class Brand
{
    public int Id { get; set; }
}

public class Category
{
    public int Id { get; set; }
}

这将输出以下请求查询

{
  "aggs": {
    "Facets": {
      "nested": {
        "path": "categories"
      },
      "aggs": {
        "categories": {
          "terms": {
            "field": "categories.id"
          }
        }
      }
    },
    "Facets2": {
      "nested": {
        "path": "brand"
      },
      "aggs": {
        "brand": {
          "terms": {
            "field": "brand.id"
          }
        }
      }
    }
  }
}