It can sometimes be quiet hard to figure out why a specific ElasticSearch query fails or don’t returns the expected results. As I’m using NEST, the high-level ElasticSearch client, it is not always obvious what is exactly happening behind the scenes.
Here is a code snippet that allows you to log the generated request and response messages:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var connectionSettings=new ConnectionSettings(CreateUri()) | |
.DisableDirectStreaming()//We do this to be able to capture the request and responses(don't do this in production!!!!) | |
.OnRequestCompleted(apiCallDetails => | |
{ | |
// log out the request and the request body, if one exists for the type of request | |
if (apiCallDetails.RequestBodyInBytes != null) | |
{ | |
Trace.Write( | |
$"{apiCallDetails.HttpMethod} {apiCallDetails.Uri} " + | |
$"{Encoding.UTF8.GetString(apiCallDetails.RequestBodyInBytes)}"); | |
} | |
else | |
{ | |
Trace.Write($"{apiCallDetails.HttpMethod} {apiCallDetails.Uri}"); | |
} | |
// log out the response and the response body, if one exists for the type of response | |
if (apiCallDetails.ResponseBodyInBytes != null) | |
{ | |
Trace.Write($"Status: {apiCallDetails.HttpStatusCode}" + | |
$"{Encoding.UTF8.GetString(apiCallDetails.ResponseBodyInBytes)}"); | |
} | |
else | |
{ | |
Trace.Write($"Status: {apiCallDetails.HttpStatusCode}"); | |
} | |
}); |
Remark: Using this code has a performance impact, so only use it for development or testing purposes.