Search code examples
c#jsonelasticsearchnest

Can you see how the JSON query looks when translated from C# Elasticsearch NEST?


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.


Solution

  • 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