Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the result of a SearchResponse in ElasticSearch

I am trying to use ES as the index for my MongoDB. I've managed to integrate them successfully, but I find the search API rather complex and confusing. The Java API is not too helpful either.

I am able to find exact matches, but how can I get this result? Here is my code:

Node node = nodeBuilder().node();

SearchResponse sr = node.client().prepareSearch()
        .addAggregation(
            AggregationBuilders.terms("user").field("admin2san")
            .subAggregation(AggregationBuilders.terms("SPT").field("64097"))
        )
        .execute().actionGet();

SearchHit[] results = sr.getHits().getHits();
List<Firewall> myfirewall = results.getSourceAsObjectList(Firewall.class);
for (Firewall info : myfirewall) {
       System.out.println("search result is " + info);
}
like image 837
LaymoO Avatar asked May 21 '15 09:05

LaymoO


2 Answers

I'm not quite sure I understood your question.

If you want to print the result of your searchResponse according to your example it should be something like this :

SearchHit[] results = sr.getHits().getHits();
for(SearchHit hit : results){
    String sourceAsString = hit.getSourceAsString();
    if (sourceAsString != null) {
        Gson gson = new GsonBuilder().setDateFormat(dateFormat)
                .create();
        System.out.println( gson.fromJson(sourceAsString, Firewall.class));
    }
}

I'm using Gson to convert from the Json response to the FireWall(POJO).

I hope it's what you were looking for.

like image 88
Samy Elaiassi Avatar answered Nov 08 '22 08:11

Samy Elaiassi


response.getHits().getHits()[0].getSourceAsMap() you could try somwthing like this

like image 1
Ksenia Erastova Avatar answered Nov 08 '22 10:11

Ksenia Erastova