c# - 使用NEST ElasticClient仅检索内部_id

标签 c# elasticsearch nest elasticsearch-net

我尝试使用NEST ElasticClient执行搜索,仅获取匹配的_id。

这是我的代码:

var client = new ElasticClient();
var searchResponse = client.Search<ElasticResult>(new SearchRequest {
         From = this.query.Page * 100,
         Size = 100,
         Source = new SourceFilter {
              Includes = "_id"
         },
         Query = new QueryStringQuery {
              Query = this.query.Querystring
         }
});

public class ElasticResult {
    public string _id;
}

但是,文档(ElasticResult-Objects)的_id始终为null。我究竟做错了什么?

最佳答案

_id不是_source文档的一部分,而是hits数组中每个匹配项的匹配项元数据的一部分。

仅返回_id字段的最紧凑方法是使用using response filtering,该方法在NEST中作为FilterPath公开

private static void Main()
{
    var defaultIndex = "documents";
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

    var settings = new ConnectionSettings(pool)
        .DefaultIndex(defaultIndex)
        .DefaultTypeName("_doc");

    var client = new ElasticClient(settings);

    if (client.IndexExists(defaultIndex).Exists)
        client.DeleteIndex(defaultIndex);

    client.Bulk(b => b
        .IndexMany<object>(new[] {
            new { Message = "hello" },
            new { Message = "world" }
        })
        .Refresh(Refresh.WaitFor)
    );

    var searchResponse = client.Search<object>(new SearchRequest<object>
    {
        From = 0 * 100,
        Size = 100,
        FilterPath = new [] { "hits.hits._id" },
        Query = new QueryStringQuery
        {
            Query = ""
        }
    });

    foreach(var id in searchResponse.Hits.Select(h => h.Id))
    {
        // do something with the ids
        Console.WriteLine(id);
    }
}

从Elasticsearch对搜索请求的JSON响应如下所示
{
  "hits" : {
    "hits" : [
      {
        "_id" : "6gs8lmQB_8sm1yFaJDlq"
      },
      {
        "_id" : "6Qs8lmQB_8sm1yFaJDlq"
      }
    ]
  }
}

关于c# - 使用NEST ElasticClient仅检索内部_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327364/

相关文章:

c# - 什么会阻止在 Azure 中的两个 Web API 应用程序之间建立连接?

python - 如何在 Python 中从 Elasticsearch 获取所有结果

elasticsearch - 如何跨嵌套文档汇总文档?

elasticsearch - 如何从远程计算机连接到 Elasticsearch 服务器?

c# - 我需要为 Nest Search 创建类型吗?

lucene - 使用文档存储作为缓存

c# - 在Elasticsearch中跨多个地址字段搜索

c# - .NET C# 组件的通知或警报框架

c# - 底层连接已关闭 : An unexpected error occurred on a send

c# - 如何从 DotnetNuke 的网页中删除页眉和页脚?