首页 > 解决方案 > 如何使用 NEST 获得不同的文档字段列表?

问题描述

我刚刚开始使用 Elasticsearch,并且正在为我的 .Net 应用程序使用 NEST API。我有一个索引和一些插入的记录。我现在正在尝试获取文档字段值的不同列表。我有这个在邮递员工作。 我不知道如何将 JSON 聚合体移植到 NEST 调用。这是我试图移植到 NEST C# API 的调用:

{
"size": 0,
"aggs": {
    "hosts": {
        "terms": {
            "field": "host"
        }
    }
}

这是我的下一个问题的结果。 我将如何解析或将 POCO 分配给结果? 在这种情况下,我只对“主机”中的字段值的不同列表感兴趣。我真的只是想要一个可枚举的字符串。我现在不在乎计数。

{
"took": 0,
"timed_out": false,
"_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
},
"hits": {
    "total": {
        "value": 3,
        "relation": "eq"
    },
    "max_score": null,
    "hits": []
},
"aggregations": {
    "hosts": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": "hoyt",
                "doc_count": 3
            }
        ]
    }
}

}

标签: elasticsearchnestelasticsearch-aggregation

解决方案


我能够使用以下代码获得我想要的结果:

        var result = await client.SearchAsync<SyslogEntryIndex>(s => s.Size(0).Aggregations(a => a.Terms("hosts", t => t.Field(f => f.Host))));

        List<string> hosts = new List<string>();
        foreach (BucketAggregate v in result.Aggregations.Values)
        {
           foreach (KeyedBucket<object> item in v.Items)
            {
                hosts.Add((string)item.Key);
            }
        }
        return hosts;

推荐阅读