5

How to convert ISearchResponse to C# Class Object.

I am trying to convert to Class Object where my Class name will be dynamic.

ISearchResponse<dynamic> bResponseNewLoop = 
    objElastic.Search<dynamic>(s => s
        .Index("index1")
        .Type("DOCTYPE")
        .From(0)
        .Size(10)
        .Source(sr => sr.Include(RequiredFields)));

From above Response , i want to convert the response object to class object and The class name i am retriving from xml file.

LosManos
  • 7,195
  • 6
  • 56
  • 107
Veena Reddy
  • 51
  • 1
  • 2

1 Answers1

7

In newer NEST versions we introduced IDocument which allows you to do lazy deserialization to the proper type.

var response = objElastic.Search<IDocument>(s => s
     .Index("index1")
     .Type("DOCTYPE")
     .From(0).Size(10)
     .Source(sr => sr.Include(RequiredFields)
);

Now on response you can loop over all the .Hits and inspect the hit metadata and use that to deserialize to the type that you want. e.g

.Hits.First().Source.As<MyDocument>()

As<>() is a method on IDocument

Martijn Laarman
  • 13,476
  • 44
  • 63
  • Thanks for your reply. – Veena Reddy Jul 02 '15 at 12:39
  • 1
    As of now, we are using NEST 4.0. But this IDocument is not suppported with above syntax in 4.0.Can you please suggest which version of the NEST is supporting this. – Veena Reddy Jul 02 '15 at 12:40
  • This has been part of `NEST` since version [1.5.0](https://github.com/elastic/elasticsearch-net/releases/tag/1.5.0) – Martijn Laarman Jul 20 '15 at 08:31
  • I just dove into version 6 and there is no `IDocument`. To make sure I compared with version 1.5 where it exists. The `IDocument` is commented as a side effect of 'inner hits' in the [release notes](https://github.com/elastic/elasticsearch-net/releases/tag/1.5.0); and 'inner hits' is/was experimental. – LosManos Nov 26 '18 at 12:34
  • Version 7 has ILazyDocument – CornelC Apr 16 '20 at 08:54