获取匹配对象子数组

Get matching objects sub array

我有一个 elasticsearch 聚合响应,想使用 jq 来过滤匹配的对象子数组以进一步提取(最后创建一个 csv 文件)

我收到如下回复:

{
  "took": 189,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 614388,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "sites_monthly_top_10": {
      "doc_count_error_upper_bound": 4507,
      "sum_other_doc_count": 205762,
      "buckets": [
        {
          "key": "this.com",
          "doc_count": 120903,
          "monthly": {
            "buckets": [
              {
                "key_as_string": "2021-03 March",
                "key": 1614556800000,
                "doc_count": 16733
              },
              {
                "key_as_string": "2021-04 April",
                "key": 1617235200000,
                "doc_count": 12744
              }
            ]
          }
        },
        {
          "key": "that.com",
          "doc_count": 81451,
          "monthly": {
            "buckets": [
              {
                "key_as_string": "2021-03 March",
                "key": 1614556800000,
                "doc_count": 4641
              },
              {
                "key_as_string": "2021-04 April",
                "key": 1617235200000,
                "doc_count": 8687
              }
            ]
          }
        }
      ]
    }
  }
}

我想处理具有键“this.com”的桶元素。匹配有效,但我仍然得到两个子元素。

cat response.json | jq -r ' .aggregations.sites_monthly_top_10.buckets | select( .[].key | contains("this.com")) | .[].monthly.buckets'

给我

[
  {
    "key_as_string": "2021-03 March",
    "key": 1614556800000,
    "doc_count": 16733
  },
  {
    "key_as_string": "2021-04 April",
    "key": 1617235200000,
    "doc_count": 12744
  }
]
[
  {
    "key_as_string": "2021-03 March",
    "key": 1614556800000,
    "doc_count": 4641
  },
  {
    "key_as_string": "2021-04 April",
    "key": 1617235200000,
    "doc_count": 8687
  }
]

但我只想访问 monthly.buckets 个匹配项。

我在这里错过了什么?

拉出 select 前面的迭代 [] 以将过滤器应用于每个数组项并保留其上下文。此外,要执行部分匹配,contains 很好,对于完全匹配,您可以使用 ==.

jq '.aggregations.sites_monthly_top_10.buckets[] | select(.key == "this.com").monthly.buckets' response.json
[
  {
    "key_as_string": "2021-03 March",
    "key": 1614556800000,
    "doc_count": 16733
  },
  {
    "key_as_string": "2021-04 April",
    "key": 1617235200000,
    "doc_count": 12744
  }
]

Demo