首页 > 解决方案 > Elasticsearch nested aggregation with nested object using NEST

问题描述

I am trying to do an aggregation on a nested object. The following is my json. The first code sample below successfully returns the productCategory Id. However, I want to return the category id and name in the aggregation. I thought I could try the second code sample below but it doesn't work.

"productCategories": [{
    "id":6,
    "productId":6,
    "categoryId":4,
    "category":{
        "parentId":2,
        "name":"Air Fresheners",
        "id":6
    }
}]

This one aggregates the productCategory id as the key:

        .Aggregations(aggs => aggs
            .Nested("agg-categories", nested => nested
                .Path(p => p.ProductCategories)
                .Aggregations(r => r
                    .Terms("agg-category", w => w
                        .Field(f => f.ProductCategories.First().Id)
                    )
                )
            )
        )

But I need the category info, and this one doesn't work:

        .Aggregations(aggs => aggs
            .Nested("agg-categories", nested => nested
                .Path(p => p.ProductCategories.First().Category)
                .Aggregations(r => r
                    .Terms("agg-category", w => w
                        .Field(f => f.ProductCategories.First().Category.Id)
                    )
                )
            )
        )

标签: elasticsearchnest

解决方案


如果category被简单地映射为object,那么以下将起作用

var searchResponse = client.Search<Document>(s => s
    .Aggregations(aggs => aggs
        .Nested("agg-categories", nested => nested
            .Path(p => p.ProductCategories)
            .Aggregations(r => r
                .Terms("agg-category", w => w
                    .Field(f => f.ProductCategories.First().Category.Id)
                )
            )
        )
    )
);

推荐阅读