如何访问从搜索聚合嵌套存储区

时间:2017-03-01 05:04:00

标签: search elasticsearch aggregation nest bucket

我有这样的查询:

var result = clientConnection.Search<dynamic>(s => s
    .Index(indexname)
    .Type(typename)
.Aggregations(a => a
    .DateRange(fieldvalue, d => d
        .Field(fieldname)

        .Ranges(
            r => r.To("2016-03-30T19:40:50+00:00"),
            r => r.From("2016-03-15T19:40:50+00:00")
        )
    )
)
);

           var agg = result.Aggs.DateRange("L2");

但是这给了我这样的2个巢桶

nest bucket

这只给我文件计数。但我需要查看文档中的值。如何检索文档中的值?我使用了Nest.BucketItem,但我无法检索它。

我也可以看到有2个桶。为什么不是1?请建议

1 个答案:

答案 0 :(得分:0)

如果您在实际文档之后,那么获取文档的查询可能就是您需要的,而不是聚合。您可以使用Multi Search API在一个请求中发出多个查询。从NEST 2.x开始,这看起来像

var indexname = "index-name";
var typename = "type-name";
var fieldname = "field-name";

var result = client.MultiSearch(ms => ms        
    .Index(indexname)
    .Type(typename)
    .Search<dynamic>("search1", s => s
        .Query(q => +q
            .DateRange(r => r
                .Field(fieldname)
                .LessThan("2016-03-30T19:40:50+00:00")
            )
        )
    )
    .Search<dynamic>("search2", s => s
        .Query(q => +q
            .DateRange(r => r
                .Field(fieldname)
                .GreaterThan("2016-03-15T19:40:50+00:00")
            )
        )
    )
);

var search1Documents = result.GetResponse<dynamic>("search1").Documents;   
var search2Documents = result.GetResponse<dynamic>("search2").Documents;

这将返回与每个查询匹配的前10个文档。您可以在每次搜索中使用.From().Size()来对结果进行分页。

修改

使用NEST 1.x,多重搜索请求看起来像

var indexname = "index-name";
var typename = "type-name";
var fieldname = "field-name";

var result = client.MultiSearch(ms => ms
    .FixedPath(indexname, typename)
    .Search<dynamic>("search1", s => s
        .Query(q => q
            .Filtered(fq => fq
                .Filter(fqf => fqf
                    .Range(r => r
                        .OnField(fieldname)
                        .Lower("2016-03-30T19:40:50+00:00")
                    )
                )
            )
        )
    )
    .Search<dynamic>("search2", s => s
        .Query(q => q
            .Filtered(fq => fq
                .Filter(fqf => fqf
                    .Range(r => r
                        .OnField(fieldname)
                        .Greater("2016-03-15T19:40:50+00:00")
                    )
                )
            )
        )
    )
);

var search1Documents = result.GetResponse<dynamic>("search1").Documents;
var search2Documents = result.GetResponse<dynamic>("search2").Documents;

如果可以的话,我建议升级到最新的5.x版本的Elasticsearch和NEST all Elasticsearch 1.x versions are now end of line for support since 16th January 2017。至少,我建议upgrading NEST to the latest 1.x version应该与Elasticsearch 1.4兼容。