【问题标题】:Retrieve only internal _id with NEST ElasticClient使用 NEST ElasticClient 仅检索内部 _id
【发布时间】:2018-12-21 23:12:44
【问题描述】:

我尝试使用 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 始终为空。我做错了什么?

【问题讨论】:

  • 你的意思是你得到了结果(文档)但是 _id 为空?
  • @LijuL:是的,就是这样。

标签: c# elasticsearch nest elasticsearch-net


【解决方案1】:

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

仅返回 _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"
      }
    ]
  }
}

【讨论】:

  • 这实际上是在进行搜索还是只是从 ES 中返回文档 ID?
  • @sramalingam24 它执行实际搜索(尽管在此示例中,空的 query_string 查询将评估为 NEST 无条件查询,因此与无查询子句相同)。
  • @RussCam 使用 FilterPath 后,响应不再包含为 null 的 scrollId。是否可以在 FilterPath 中指定 scrollId?我尝试了“scrollId”和“scroll_id”,但都不起作用。
猜你喜欢
  • 2015-05-15
  • 2019-08-04
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多