V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
sniperking1234

求助 es 多层聚合查询问题

  •  
  •   sniperking1234 · Nov 11, 2020 · 4857 views
    This topic created in 2005 days ago, the information mentioned may be changed or developed.

    数据结构如下所示

    {
      "id": 1234,
      "operationName": "harbor-harbor-core.harbor.svc.cluster.local:80/service/*",
      "duration": 145428,
      "tags": [
        {
          "key": "guid:x-request-id",
          "type": "string",
          "value": "bccfdfa4-86e6-9f47-a41e-d56f7b4e5a88"
        },
        {
          "key": "http.url",
          "type": "string",
          "value": "http://baidu.com"
        }
      ]
    }
    

    我想根据 tags 中 key 为 http.url 这个字段,聚合出 url 的数量,并且算出每个 url 的平均访问时间,也就是算 avg duration 字段。现在我用下面的查询可以对 url 以及数量进行聚合,但是不知道怎么算 avg duration 。

    {
      "size": 0,
      "aggs": {
        "tags": {
          "nested": {
            "path": "tags"
          },
          "aggs": {
            "key": {
              "filter": {
                "term": {
                  "tags.key": "http.url"
                }
              },
              "aggs": {
                "values": {
                  "terms": {
                    "field": "tags.value"
                  }
                }
              }
            }
          }
        }
      }
    }
    

    求助 es 大神,如何写查询能够计算出 avg duration

    1 replies    2020-11-11 17:17:48 +08:00
    weofuh
        1
    weofuh  
       Nov 11, 2020   ❤️ 1
    你需要 reverse_nested

    {
    "size": 0,
    "aggs": {
    "tags": {
    "nested": {
    "path": "tags"
    },
    "aggs": {
    "key": {
    "filter": {
    "term": {
    "tags.key": "http.url"
    }
    },
    "aggs": {
    "values": {
    "terms": {
    "field": "tags.value"
    },
    "aggs": {
    "url_duration_avg": {
    "reverse_nested": {},
    "aggs": {
    "duration_avg":{
    "avg": {
    "field": "duration"
    }
    }
    }
    }
    }
    }
    }
    }
    }
    }
    }
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4644 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:04 · PVG 18:04 · LAX 03:04 · JFK 06:04
    ♥ Do have faith in what you're doing.