LaymoO
LaymoO

Reputation: 107

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);
}

Upvotes: 8

Views: 24391

Answers (2)

Samy Elaiassi
Samy Elaiassi

Reputation: 516

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.

Upvotes: 15

Ksenia Erastova
Ksenia Erastova

Reputation: 11

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

Upvotes: 1

Related Questions