我怎样才能在Elasticsearch中计算aggs组

pwuypxnk  于 2023-02-11  发布在  ElasticSearch
关注(0)|答案(1)|浏览(147)

我在Elastic search中编写了一些查询来计算索引中的事件,我认为我的构造是正确的,但是当我可以从aggs组中获得搜索结果时,实际上我想要的是计数,而不是结果。
我的背景知识是SQL,我尝试执行的等效查询是:

SELECT
  COUNT(1) as volume
FROM (
      SELECT
      key
    , type
    , ROW_NUMBER() OVER( PARTITION BY key ORDER BY timestamp DESC ) AS instance
  FROM event
  ) A
WHERE type != 'Delete'
AND instance = 1

简单地说,这就是:按键计算最新事件的事件量,不包括删除
我已经尝试了以下弹性:

GET /index/_search
{
  "size": 0,
  "aggs": {
    "group_by_key": {
      "terms": {
        "field": "key",
        "size": 1000000
      },
      "aggs": {
        "top_record_per_group": {
          "top_hits": {
            "sort": [
              {
                "timestamp": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  },
  "query": {
    "bool": {
      "must_not": [
        {
          "term": {
            "type": "Delete"
          }
        }
      ]
    }
  }
}

...而这确实返回了我所期望的。我知道count API,也知道它不支持aggs。
有谁能帮我指出我遗漏的一点,并希望告诉我最有效的方法来获得价值的体积只(即没有其他结果)?
先谢了
编辑:
一个可行的例子是

key type    timestamp   latest? include?
1   insert  00:00:01    
1   update  00:00:02        
2   insert  00:00:03        
3   insert  00:00:04    Y       Y
2   delete  00:00:05    Y       N
4   insert  00:00:06        
1   update  00:00:07    Y       Y
4   update  00:00:08    Y       Y

volume: 3
htzpubme

htzpubme1#

如果只需要count,则可以使用值count aggs。
我还将使用过滤器来改进该高速缓存并提高查询的性能。

GET /test/_search
{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "must_not": [
              {
                "term": {
                  "type": "Delete"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "aggs": {
    "count_volume": {
      "value_count": {
        "field": "key"
      }
    }
  }
}

相关问题