Alexander Tunick
Alexander Tunick

Reputation: 525

Elasticsearch. Get count of values in a field of specific index

Tried to find any method to retrieve count on values in a specific field. But so far I did not find appropriate method in Elastic API documentation.

enter image description here

Let's consider I have this basic piece of code:

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
});

I need to get count from index "persons", field "dri"

Upvotes: 0

Views: 1610

Answers (2)

Alexander Tunick
Alexander Tunick

Reputation: 525

Following the example above and taking Tarek's answer as the start point I researched this body query that returns exactly what I need: count of values in the exact field.

const getFieldCount = (field) => client.count({
            index: 'institutions',
            body: {
                query: {
                    bool: {
                        must:[
                            { "exists": {"field": "library_type_id"} }
                        ],
                    },
                },
            },
        });

Upvotes: 1

Tarek Essam
Tarek Essam

Reputation: 4000

This will get you the number a certain field in the persons index (which will be the same number of docs in the index if the field exists in all of the docs):

 const getFieldCount = (field) => client.search({
    size: 0,
    index: 'persons',
    body: {
      query: { match_all: {} },
      aggs: {
        field_count: {
            value_count: {
            field,
          },
        },
      },
    },
  });

  getFieldCount('dri')
    .then((res) => console.log(res));

Upvotes: 2

Related Questions