代码之家  ›  专栏  ›  技术社区  ›  BennoDual

仅检索具有Nest ElasticClient的内部\u id

  •  0
  • BennoDual  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Russ Cam    7 年前

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

    最紧凑的返回方式 小精灵 字段将与 using response filtering 暴露于 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"
          }
        ]
      }
    }