Milux
Milux

Reputation: 408

Elasticsearch having count(*)= n

I have a simple index (in elasticsearch) and need to execute a query that is available in SQL databases.

my-index structure:

'{"id":"1","userid":"1"}'
'{"id":"2","userid":"1"}'
'{"id":"3","userid":"1"}'
'{"id":"4","userid":"2"}'
'{"id":"5","userid":"3"}'

now I need to execute this query :

select count(userid),userid from my-index  group by userid having count(userid)=3;

Is it possible to execute such queries in elasticsearch?

Upvotes: 2

Views: 3105

Answers (1)

Bhavya
Bhavya

Reputation: 16172

You can use terms aggregation along with bucket selector aggregation

Adding a working example with index mapping, search query, and search result

Index Mapping:

{
  "mappings": {
    "properties": {
      "userid": {
        "type": "keyword"
      }
    }
  }
}

Search Query:

{
  "size": 0,
  "aggs": {
    "userId": {
      "terms": {
        "field": "userid"
      },
      "aggs": {
        "the_filter": {
          "bucket_selector": {
            "buckets_path": {
              "the_doc_count": "_count"
            },
            "script": "params.the_doc_count == 3"
          }
        }
      }
    }
  }
}

Search Result:

"aggregations": {
    "userId": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "1",              // this denotes the userid having count==3
          "doc_count": 3
        }
      ]
    }

Upvotes: 3

Related Questions