hello_its_me
hello_its_me

Reputation: 793

Elasticsearch Java API: Return a boolean value

I need to build a query that returns a boolean value that Java could read. When I try this:

 QueryBuilder qb = matchQuery(
     "user.name",                  
     "user123"
 );
 SearchResponse response = client.prepareSearch("logstash-*").addFields("user.name")
.setTypes("names").setQuery(qb)
.execute()
.actionGet();

It returns all the hits for user123. If user123 doesn't exist, it returns the following:

 {
   "took" : 69,
"timed_out" : false,
"_shards" : {
  "total" : 75,
  "successful" : 75,
  "failed" : 0
},
"hits" : {
  "total" : 0,
  "max_score" : null,
  "hits" : [ ]
}
   }

What I need, however, is a true or false value. If the user exists, then true, if not, then false. How can I accomplish that?

Thank you.

Upvotes: 0

Views: 456

Answers (1)

yyk
yyk

Reputation: 130

How about Count API and check if the result is 0 or not?

QueryBuilder qb = matchQuery(
 "user.name",                  
 "user123"
);
SearchResponse response = client.prepareCount("logstash-*").addFields("user.name")
                      .setTypes("names").setQuery(qb)
                      .execute()
                      .actionGet();
return response.count() != 0 // return true if found

Upvotes: 1

Related Questions