5

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

Community
  • 1
  • 1
richardwhatever
  • 4,564
  • 5
  • 23
  • 26

2 Answers2

6

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);
}
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
Duoc Tran
  • 834
  • 14
  • 18
4

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.

Martijn Laarman
  • 13,476
  • 44
  • 63
  • Hi Martijn, When I try this it gives me stack overflow. return new HttpResult(search); Where 'search' is an ISearchResponse. How am I supposed to pass this out of servicestack? Thanks. – richardwhatever Nov 19 '14 at 21:37
  • Stream holds the raw json as to be send by elasticsearch, you can simply read it your self and send it down the wire as json string or more elaborately use something like http://msdn.microsoft.com/en-us/library/system.net.http.pushstreamcontent%28v=vs.118%29.aspx to stream directly to the web api response. If you go with string you can also use `Search` The key to note here is that the response is already json as a string or stream, no need for SS.Text to serialize anything. – Martijn Laarman Nov 24 '14 at 10:56
  • Hi Martijn, Sorry, but i'm unable to get this to work. Could you possibly give an example of calling .Search and manipulating the result into a standard string variable? Many thanks! – richardwhatever Sep 03 '15 at 18:38