Returning Search Results as JSON


(James Cook-3) #1

I work in SSJS, so JS access to elasticsearch is pretty much second nature:

var searchResponse = getClient().search(request).actionGet();
var searchHits = searchResponse.hits().hits();

return searchHits.map(function(hit) {
return JSON.parse(hit.sourceAsString());
});

You might notice that I am iterating over search hits only here. Now, I
want access to facets and other information at a higher level than just
hits. How might I take a SearchResult object and convert it to a JSON
string value? I am assuming the REST interface does this, but I didn't find
where the magic happens.


(Lukáš Vlček) #2

Hi James,

I am working in a little different scenario, no SSJS (assuming this stands for Server Side JS). In my case I return JSON form servlet proxy and consume it on the client side (web browser). And I do it like this, may be this will help:

        ServletOutputStream os = (HttpServletResponse) response.getOutputStream();

        … do the search and get search response ...

        XContentBuilder builder = XContentFactory.jsonBuilder(os);
        builder.startObject();
        searchResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        builder.close();


        os.close();  

--
Regards,
Lukas

On Tuesday, December 6, 2011 at 11:04 PM, James Cook wrote:

I work in SSJS, so JS access to elasticsearch is pretty much second nature:

var searchResponse = getClient().search(request).actionGet();
var searchHits = searchResponse.hits().hits();

return searchHits.map(function(hit) {
return JSON.parse(hit.sourceAsString());
});

You might notice that I am iterating over search hits only here. Now, I want access to facets and other information at a higher level than just hits. How might I take a SearchResult object and convert it to a JSON string value? I am assuming the REST interface does this, but I didn't find where the magic happens.


(James Cook-3) #3

Thanks Lucas. I'll give it a shot. I haven't played with XContentBuilders
yet, so I guess it is time. Seems like a convenience method ( toJSON() )
would be welcome.


(Shay Banon) #4

SearchResponse.#toString will return you a json string, though you probably
don't want to do that since its the less efficient way to stream it back to
the client.

On Wed, Dec 7, 2011 at 4:54 PM, James Cook jcook@pykl.com wrote:

Thanks Lucas. I'll give it a shot. I haven't played with XContentBuilders
yet, so I guess it is time. Seems like a convenience method ( toJSON() )
would be welcome.


(James Cook-3) #5

I didn't know that. That is even easier. There is no streaming to client
involved because this is an embedded ES instance. Thanks.


(system) #6