Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "pass through" the raw json response from a NEST Elasticsearch query?

Our client side code works directly with elasticsearch responses, but I want to put NEST in the middle to do some security and filtering. What is the easiest way to build a query with NEST (or elasticsearch.net) and then just pass the raw json response back out to my client with the least amount of processing. I'm using ServiceStack as well by the way.

Previous similiar question has now an outdated answer - Returning Raw Json in ElasticSearch NEST query

Thanks

like image 725
richardwhatever Avatar asked Nov 05 '14 09:11

richardwhatever


2 Answers

This is for the benefit of readers who want to achieve the same thing in newer versions of NEST, v2.3 as of this writing. If you just want the response, all you need to do is this using the ElasticLowLevelClient, according to the doc:

var responseJson = client.Search<string>(...);

But if you want the typed results as well then it's slightly more involved. You need to call DisableDirectStreaming() on the settings object and then retrieve the raw json from response.ApiCall.ResponseBodyInBytes as demonstrated here.

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

var response = new ElasticClient(settings)
           .Search<object>(s => s.AllIndices().AllTypes().MatchAll());

if (response.ApiCall.ResponseBodyInBytes != null)
{
    var responseJson = System.Text.Encoding.UTF8.GetString(response.ApiCall.ResponseBodyInBytes);
}
like image 171
Duoc Tran Avatar answered Oct 21 '22 00:10

Duoc Tran


Elasticsearch.Net allows you to return the response stream directly,

var search = client.Search<Stream>(new { size = 10 });

.Search() has many overloads to limit its scope by index and type.

This will return an IElasticsearchResponse<Stream> where you can pass the response stream directly to the deserializer of your choide (SS.Text in your case) without the client buffering in between.

like image 20
Martijn Laarman Avatar answered Oct 20 '22 23:10

Martijn Laarman