Athena 查询不带结构的 JSON 数组

问题描述 投票:0回答:1

在 Athena 中,如何构造一个 select 语句来按时间戳查询以下内容?数据存储为字符串

[{
    "data": [{
        "ct": "26.7"
    }, {
        "ct": "24.9",
    }, {
        "ct": "26.8",
    }],
    "timestamp": "1658102460"
}, {
    "data": [{
        "ct": "26.7",
        }, {
        "ct": "25.0",
        }],
    "timestamp": "1658102520"
}]

我尝试了下面的方法,但它只是空空如也。

SELECT json_extract_scalar(insights, '$.timestamp') as ts
FROM history

我想要得到的只是返回时间戳位于 X 和 Y 之间的数据。

当我尝试将其作为结构体和与 unnest 的交叉连接时,它非常非常慢,所以我正在尝试寻找另一种方法。

sql aws-glue amazon-athena presto
1个回答
1
投票

json_extract_scalar
在这里没有帮助,因为它只返回一个值。 Trino 极大地改进了 json path 支持,但 Athena 有更旧版本的 Presto 引擎,不支持它。因此,您需要转换为数组并使用
unnest
(从 json 中删除尾随逗号):

-- sample data
WITH dataset (json_str) AS (
    values ('[{
    "data": [{
        "ct": "26.7"
    }, {
        "ct": "24.9"
    }, {
        "ct": "26.8"
    }],
    "timestamp": "1658102460"
}, {
    "data": [{
        "ct": "26.7"
        }, {
        "ct": "25.0"
        }],
    "timestamp": "1658102520"
}]')
)

-- query
select mp['timestamp'] timestamp,
    mp['data'] data
from dataset,
unnest(cast(json_parse(json_str) as array(map(varchar, json)))) as t(mp)

输出:

时间戳 数据
1658102460 [{"ct":"26.7"},{"ct":"24.9"},{"ct":"26.8"}]
1658102520 [{"ct":"26.7"},{"ct":"25.0"}]

之后您可以应用过滤和处理

data

© www.soinside.com 2019 - 2024. All rights reserved.