0

In the documentation here https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/writing-queries.html

It gives an example that this C# query with Fluent API

var searchResponse = client.Search<Project>(s => s
    .Query(q => q
    .MatchAll()
));

will translate into this json query:

{
   "query": {
   "match_all": {}
   }
}

This is all good, but i want to see it for myself in the code. So now my question is - is it possible to get the JSON string in my C# code?

I need it because, i want to see how NEST translates the C# query into JSON when i make some more complicated queries such as big aggregations.

Then i can see how it looks in JSON, and see if it translated it into the JSON i expected.

Danny Chu
  • 83
  • 1
  • 7
  • Go to the github project and read the code. There's no other way. I'd guess they construct a query object and serialize it to json using a library like JSON.NET. Or it could be that each operator emits a specific string. – Panagiotis Kanavos Mar 09 '18 at 10:15
  • Source for [Search](https://github.com/elastic/elasticsearch-net/blob/e2223918fc95e08872ed15d35bbed16c609601f8/src/Nest/Search/Search/ElasticClient-Search.cs#L59) shows the lambda returns an ISearchRequest object when invoked. After that, things get complex as the client uses its own JSON serializer and transport mechanism with large parts generated from the API specification. The calls end up to this [method](https://github.com/elastic/elasticsearch-net/blob/96dff79b75eecf46cb5db927060166bda979edd7/src/Nest/_Generated/_LowLevelDispatch.generated.cs#L2658) that calls `_lowLevel.SearchGet` – Panagiotis Kanavos Mar 09 '18 at 10:37
  • Searching for `SearchGet` returns only the same match. There's probably a code-generation step that creates the call. It's best to do what the answer to the duplicate question proposes. Greg Marzouka is one of the maintainers of the client – Panagiotis Kanavos Mar 09 '18 at 10:39

1 Answers1

2

I just found out myself. Heres the code:

var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
   .DisableDirectStreaming()
   .DefaultIndex("sales");
var client = new ElasticClient(settings);

var searchResponse = await client.SearchAsync<Sales>(x => x
   .Size(0)
   .MatchAll()
);

if (searchResponse.ApiCall.ResponseBodyInBytes != null)
{
   var requestJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.RequestBodyInBytes);
   Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(requestJson), Formatting.Indented));
}

Remember to set .DisableDirectStreaming() in the ConnectionSettings

Danny Chu
  • 83
  • 1
  • 7