Elastic Search (COUNT*) with group by and where condition

故事扮演 提交于 2021-02-18 15:00:08

问题


Dear Elastic Serach users,

I am newbie in ElasticSearch.

I am confused for how to convert the following sql command into elasticSearch DSL query ? Can anyone help to assist me.

SELECT ip, count(*) as c  FROM elastic WHERE  date 
BETWEEN '2016-08-20  00:00:00' and '2016-08-22 13:41:09' 
AND service='http' AND destination='10.17.102.1' GROUP BY ip ORDER BY c DESC;

THank YOu


回答1:


The following query will achieve exactly what you want, i.e. it will select the documents within the desired date range and with the required service and destination and then run a terms aggregation (=group by) on their ip field and order the latter in decreasing count order.

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gt": "2016-08-22T00:00:00.000Z",
              "lt": "2016-08-22T13:41:09.000Z"
            }
          }
        },
        {
          "term": {
            "service": "http"
          }
        },
        {
          "term": {
            "destination": "10.17.102.1"
          }
        }
      ]
    }
  },
  "aggs": {
    "group_by_ip": {
      "terms": {
        "field": "ip"
      }
    }
  }
}


来源:https://stackoverflow.com/questions/39113842/elastic-search-count-with-group-by-and-where-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!