Display elastic search hits values using NEST

2019-09-01 06:44发布

问题:

I am using following code for searching the articleid and control fields. it will hold the 2 fields values. But I can't access these two fields values. HERE search<> is dynamic.

  var searchrange = _client.Search<dynamic>(s =>  s
               .Indices("kb_v2").Types("kb")
               .From(0).Size(10)
               .Fields("articleid","control")
               .Query(q => q
                     .Range(r =>r
                         .OnField("articleid")
                         .Greater("2")
                         .Lower("5"))));

can you explain How to get the this two fields values..

回答1:

Since Elasticsearch 1.0 fields are always returned as a Dictionary<string, object[]> on hits to access these in NEST you can use:

foreach (var doc in queryResults.FieldSelections)
{
    var articleIds = doc.FieldValues<int[]>("articleid");
}

See this PR for more details on the syntax.



回答2:

The search response (ISearchResponse type) has a FieldSelections property which holds the results and details. With the older version of Nest, one had to loop over the Hits property to find the value of each field.

"hits": [
         {
            "_index": "kb_v2",
            "_type": "kb",
            "_id": "3565178",
            "_score": 1,
            "fields": {
               "articleid": [
                  "3"
               ]
            }
         },
         {
            "_index": "kb_v2",
            "_type": "kb",
            "_id": "3932480",
            "_score": 1,
            "fields": {
               "articleid": [
                  "4"
               ]
            }
         }]

More on how to use the FieldSelections in ElastichSearch.net client is mentioned in this Unit test here