Hive:如何分解嵌入在 CSV 文件中的 JSON 列?

pro*_*lad 6 csv json hadoop hive explode

从 CSV 文件(带有标题和管道分隔符)我得到了以下两个内容,其中包含一个 JSON 列(里面有一个集合),如下所示:

第一种情况(使用没有名称的 JSON 集合):

ProductId|IngestTime|ProductOrders
9180|20171025145034|[{"OrderId":"299","Location":"NY"},{"OrderId":"499","Location":"LA"}]
8251|20171026114034|[{"OrderId":"1799","Location":"London"}]
Run Code Online (Sandbox Code Playgroud)

第二种情况(使用名为“Orders”的 JSON 集合):

ProductId|IngestTime|ProductOrders
9180|20171025145034|{"Orders":[{"OrderId":"299","Location":"NY"},{"OrderId":"499","Location":"LA"}]}
8251|20171026114034|{"Orders":[{"OrderId":"1799","Location":"London"}]}
Run Code Online (Sandbox Code Playgroud)

首先,我像这样创建我的“原始”表:

DROP TABLE IF EXISTS Product;
CREATE EXTERNAL TABLE Product (
  ProductId STRING,
  IngestTime STRING,
  ProductOrders STRING
)
COMMENT "Product raw table"
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\|'
STORED AS TEXTFILE
LOCATION
  '/data/product'
TBLPROPERTIES ("skip.header.line.count"="1");
Run Code Online (Sandbox Code Playgroud)

当我查询我的表时:

SELECT * FROM Product
Run Code Online (Sandbox Code Playgroud)

我有以下答案:

第一种情况(使用没有名称的 JSON 集合):

ProductId  IngestTime      ProductOrders
9180       20171025145034  [{"OrderId":"299","Location":"NY"},{"OrderId":"499","Location":"LA"}]
8251       20171026114034  [{"OrderId":"1799","Location":"London"}]
Run Code Online (Sandbox Code Playgroud)

第二种情况(使用名为“Orders”的 JSON 集合):

ProductId  IngestTime      ProductOrders
9180       20171025145034  {"Orders":[{"OrderId":"299","Location":"NY"},{"OrderId":"499","Location":"LA"}]}
8251       20171026114034  {"Orders":[{"OrderId":"1799","Location":"London"}]}
Run Code Online (Sandbox Code Playgroud)

好的,非常好,到目前为止它运行良好!

但我现在需要的是创建一个 SELECT 查询,它返回:

ProductId  IngestTime      ProductOrderId ProductLocation
9180       20171025145034  299            NY
9180       20171025145034  499            LA
8251       20171026114034  1799           London
Run Code Online (Sandbox Code Playgroud)

我真的需要一个可移植的 SQL 查询,它适用于我的两种情况(有或没有标签“OrderId”)。

到目前为止,我通过使用'explode'、'get_json_object'等尝试了很多组合,但我仍然没有找到正确的SQL查询。

非常感谢你的帮助 :-)

小智 -1

你可以试试

CREATE EXTERNAL TABLE product(productid String,ingesttime String, productorders array<struct<orderid:String,location:string>> ) 

select productid,ingesttime, productorders.orderid[0] as orderid , productorders.location[0] as location from product
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述