无法访问 AWS Athena 中的数组元素

Cannot access Array elements in AWS Athena

我有一个 .txt 文件,其中包含用括号括起来的逗号分隔字符串数组的列,我想在 AWS Athena/QS 中对其执行一些分析。 原始数据如下所示:

col_id    col2
1         ["string1", "string2", "string3", "string4"] 
2         ["string1", "string2"]
3         ["string1", "string2", "string3"]
...

我在 Athena 中创建了一个 table,其中包含以下内容:

create external table db.xx (
    col1 string,
    col2 array<string>

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'serialization.format' = '  ',
  'field.delim' = ' ',
  'collection.delim' = ','
) LOCATION 's3://xxx'
TBLPROPERTIES ("skip.header.line.count"="1");

table创建成功,列被识别为数组数据类型。

但是我无法访问数组中的元素。

select element_at(col2,1) 来自 table returns:

string1, string2, string3, string4
string1, string2
string1, string2, string3

我也试过从原始数据中删除 [] 和 "",但仍然得到相同的结果。

CSV 没有数组类型,可以通过多种方式对数组进行编码。遗憾的是,Athena 不会自动找出您的数据的处理方式,即使您说某列的类型为 array<string>.

但是,有一个解决方法:使用 string 作为列类型,然后在查询时将值转换为 JSON(因为看起来您的数组编码方式为 JSON 编码字符串数组),或使用 the many JSON functions 之一从数组中提取值:

像这样创建 table:

create external table db.xx (
    col1 string,
    col2 string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'serialization.format' = '  ',
  'field.delim' = ' ',
  'collection.delim' = ','
) LOCATION 's3://xxx'
TBLPROPERTIES ("skip.header.line.count"="1");

然后这样查询:

SELECT
  col1,
  json_array_get(col2, 0)
FROM db.xx