Himanshu121
Himanshu121

Reputation: 87

NEST : Issue in getting data from search response (ISearchResponse) in ElasticSearch

I wrote a C# code using NEST, which makes search queries to my ES database. I can see these queries succeed and give a json response body through Postman. I want to use these responses in my code. For example,

ISearchResponse<class> myquery = client.Search<class>(...) (some successful api call)

The response body is something like:

{
  "took": 5,
  ...
  ...
  "hits": {
    "max_score": 1.2,
    "hits": [
      {
        "_index": "sample",
        ...
        "_source": {
          "name": "generic name",
          "profession": "lawyer",
          ...
        }
      }
    ]
  }
    "aggs" : {
       ...
    }
}

I can get the "took" value here by doing myquery.Took. Similarly I can see the definition of ISearchResponse<> contains data members for MaxScore, TimedOut etc.

My question is, In the same way if I want to get the value of, say the name field or some bucket in aggr, to use in my code. How can I do this? Please Help.

Note : The Documentation only explained how to handle error responses and I can see in the debugger that probably .Documents is storing this somehow, but I'm not able to retrieve the data (or probably I can't understand how to). So please also explain how to get it from .Documents if that is the case.

Upvotes: 3

Views: 1080

Answers (1)

Russ Cam
Russ Cam

Reputation: 125518

The "_source" JSON object of each hit will be deserialized into the type T specified as the generic type parameter on Search<T>. In your example, "_source" will be deserialized into class, so simply define properties on class for the properties on "_source". For example

public class MyDocument 
{
    [PropertyName(Name = "name")]
    public string Name {get;set;}

    [PropertyName(Name = "profession")]
    public string Profession {get;set;}
}

var response = client.Search<MyDocument>();

Upvotes: 4

Related Questions