Jayesh Agarwal
Jayesh Agarwal

Reputation: 131

How to get count of documents that match a certain condition in Elasticsearch

Suppose, I have a MongoDB query

db.tm_watch.count({trademark: {$in: [ObjectId('1'), ObjectId('2')]}});

that returns the count of documents that have trademark equal to 1 or 2. I have tried this query to convert it into elasticsearch one.

 es_query = {
    "query": {
       "bool": {
          "must": [
                     {"terms": {"trademark": ids}},
                     {"term": {"team": req.user.team.id}},
                  ],
                }
              }
            }
 esClient.count({
    index: 'tm_watch',
    type: 'docs',
    body: es_query
}

but I don't know is this correct since I'm new to Elasticsearch. Thanks!

Upvotes: 1

Views: 2068

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16943

The ES equivalent to mongodb's .count method is the Count API.

Assuming your index name is tm_watch and the field trademark has a .keyword multi-field mapping, you could use a terms query:

POST tm_watch/_count
{
  "query": {
    "terms": {
      "trademark.keyword": [ "1", "2" ]
    }
  }
}

Upvotes: 1

Related Questions