Is it possible to use ElasticSearch.Net or Nest for dynamic response

1.1k Views Asked by At

Is there a client.Read(...) without generics? I have found none, neither in Nest nor ElasticSearch.Net.


Version 1.5 has an IDocument that might solve my problem but I cannot use that version with Elasticsearch5.5.

All examples, version 5 and 6, of ElasticSearch.Net and Nest require me to know the format of the response as generic at compile time. E.g. Read<Customer>(...)

My problem is that the we do not know the format of the database and we don't know the format of the output; but it should all be configurable.

2

There are 2 best solutions below

0
On BEST ANSWER

You can use dynamic as the generic type if the response is truly dynamic.

In 5.x, this will be Json.NET's JObject type under the covers (so you could use JObject instead if you prefer).

In 6.x, dynamic will also work but the actual type will be an internal JObject type. If you would prefer to work with Json.NET's JObject type, you can hook up Json.NET as the serializer using the NEST.JsonNetSerializer nuget package, to use as the serializer for your documents and then use its JObject type as per 5.x.

0
On

(Feels strange to answer my own question but I want to show the resulting code for future reference.)

var settings = new ConnectionSettings(new Uri(@"http://localnhost:9200"))
    .DefaultIndex("myindex");
var client = new ElasticClient(settings);

var res = client.Search<dynamic>(s => s
    .AllTypes());

var rows = res.Documents;
Assert.IsTrue(rows.Count >= 1);

dynamic row = res.Documents.First();
Assert.AreEqual("50.7031526", row.POSITION.lat.ToString()); // It is case sensitive.
Assert.AreEqual(50.7031526, (double)row.POSITION.lat); // Convert to type explicitly.