首页 > 解决方案 > Elasticsearch - 使用 jq 导出到 CSV

问题描述

我正在将数据从 Elasticsearch 导出到 CSV。我从可视化的请求元素中获取了我的 JSON 代码,通过 curl XGET 搜索执行它并将其通过管道传输到 jq。我的问题是 jq 如何处理这个输出。暂时跳过 jq 部分,搜索的输出显示 aggs 有好几层。例如

curl -XGET "http://localhost:9200/kibana_sample_data_flights/_search" -H 'Content-Type: application/json' -d '{"aggs": {"2": {"date_histogram": {"field": "timestamp","interval":"30m","time_zone": "Europe/London","min_doc_count": 1},"aggs": {"3": {"terms": {"field": "FlightDelayType","size": 5,"order": {"_count": "desc"}}}}}},"size":0,"_source": {"excludes": []},"stored_fields": ["*"],"script_fields": {"hour_of_day": {"script": {"inline": "doc['timestamp'].value.hourOfDay","lang": "painless"}}},"docvalue_fields": [{"field": "timestamp","format": "date_time"}],"query": {"bool": {"must": [{"match_all": {}},{"match_all": {}},{"range": {"timestamp": {"gte": 1542804577190,"lte": 1542890977190,"format": "epoch_millis"}}}],"filter": [],"should": [],"must_not": []}}}'

突出显示我的问题的输出片段:

"aggregations" : {
"2" : {
  "buckets" : [
    {
      "key_as_string" : "2018-11-21T12:30:00.000Z",
      "key" : 1542803400000,
      "doc_count" : 2,
      "3" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : "No Delay",
            "doc_count" : 1
          },
          {
            "key" : "Weather Delay",
            "doc_count" : 1
          }
        ]
      }
    },

我似乎无法让我的 jq 代码横向向下到“3”下的层。我真正想在这里发送到 CSV 的是关键的航班延误类型(例如天气延误)和计数。(注意我省略了 -r 和 | @CSV 进行测试。)到目前为止我的 jq 代码:

jq '.aggregations[].buckets[]'

那返回:

    {
  "buckets": [
    {
      "key_as_string": "2018-11-21T12:30:00.000Z",
      "key": 1542803400000,
      "doc_count": 2,
      "3": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "No Delay",
            "doc_count": 1
          },
          {
            "key": "Weather Delay",
            "doc_count": 1
          }
        ]
      }
    },

我怎样才能得到下一层?

TIA

标签: jsonelasticsearchexport-to-csvjq

解决方案


从顶部向下钻取:

.aggregations[].buckets[]["3"].buckets[] | select( .key == "Weather Delay")

产量:

{
  "key": "Weather Delay",
  "doc_count": 1
}

或者 ...

...如果您愿意冒险:

.. | select(.key? == "Weather Delay")

推荐阅读