AbhayV
AbhayV

Reputation: 29

How to get the total documents count, containing a specific field, using aggregations?

I am moving from ElasticSearch 1.7 to 2.0. Previously while calculating Term Facets I got the Total Count as well. This will tell in how many documents that field exists. This is how I was doing previously.

TermsFacet termsFacet = (TermsFacet) facet;
termsFacet.getTotalCount();

It worked with Multivalue field as well.

Now in current version for Term Aggregation we don't have anything as Total Count. I am getting DocCount inside Aggregation bucket. But that will not work for muti-valued fields.

Terms termsAggr = (Terms) aggr;
for (Terms.Bucket bucket : termsAggr.getBuckets()) {
                    String bucketKey = bucket.getKey();
                    totalCount += bucket.getDocCount();
 }

Is there any way I can get Total count of the field from term aggregation. I don't want to fire exists Filter query. I want result in single query.

Upvotes: 1

Views: 877

Answers (1)

Jettro Coenradie
Jettro Coenradie

Reputation: 4733

I would use the exists query: https://www.elastic.co/guide/en/elasticsearch/reference/2.x/query-dsl-exists-query.html

For instance to find the documents that contain the field user you can use:

{
    "exists" : { "field" : "user" }
}

There is of course also a java API: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-term-level-queries.html#java-query-dsl-exists-query

QueryBuilder qb = existsQuery("name"); 

Upvotes: 1

Related Questions