【问题标题】:How to flatten a json structure in HIVE?如何在 HIVE 中展平 json 结构?
【发布时间】:2021-12-26 03:09:12
【问题描述】:

我有一个像这样的 JSON 结构。 有一个结构嵌套在一列中。

标题:

{"user":{"location":"USA","id":1514008171,"name":"Auzzie Jet","screenname":"metalheadgrunge","geoenabled":false},"tweetmessage":"Anthrax - Black - Sunglasses hell","createddate":"2013-06-20T12:08:44","identifier":"1234","geolocation":null}

当我查询这个时,这有效:

SELECT *
FROM TBL a
WHERE header.identifier = '1234'

但是,当我想从嵌套的 json 结构中找到位置时。它不起作用:

SELECT *
FROM TBL a
WHERE header.identifier = '1234'
and a.header.user.location LIKE '%USA%'

有人知道如何在 HIVE 中查询吗?

【问题讨论】:

    标签: sql hadoop hive hiveql


    【解决方案1】:

    对于扁平化 json 结构,您需要首先使用 json_tuple 创建 lateral view,这样您才能实现您的目标。 请找到完整的解决方案。

    第 1 步:使用数据类型为字符串的单列推文创建外部表推文。

    CREATE EXTERNAL table tweets (tweet string);

    现在把json字符串 {"user":{"location":"USA","id":1514008171,"name":"Auzzie Jet","screenname":"metalheadgrunge","geoenabled":false},"tweetmessage":"Anthrax - Black - Sunglasses hell","createddate":"2013-06-20T12:08:44","identifier":"1234","geolocation":null}

    第 2 步:在名为 tweets.txt 的文本文件中运行以下命令,将文本文件中的数据加载到 hive 表中。

    LOAD data local inpath 'tweets.txt' into table tweets;

    一旦完成,现在我们就可以使用我们的 Json 字符串了。

    所以基本上我们在这里尝试实现的是查询基本上处于不同级别的标识符和位置字段。

    user
        location    :   USA
        id          :   1514008171
        name        :   Auzzie Jet
        screenname  :   metalheadgrunge
        geoenabled  :   false
    tweetmessage    :   Anthrax - Black - Sunglasses hell
    createddate :   2013-06-20T12:08:44
    identifier  :   1234
    geolocation :   null
    

    1 级字段为 => user、tweetmessage、createddate、identifier、geolocation 2 级字段为 => location、id、name、screenname、geoenabled

    所以首先我们需要在 Level 1 上创建横向视图,以便我们可以查询 Level 1 字段。在我们的示例中,我们需要查询identifier。此外,为了查询 2 级字段,我们需要展开我们的用户视图,这可以通过横向视图实现。

    LATERAL VIEW json_tuple(t.tweet, 'user', 'identifier' ) t1 as `user`, `identifier`
    

    然后要查询location,我们需要为二级字段创建另一个横向视图。

    LATERAL VIEW json_tuple(t1.`user`,'name', 'location') t2 as `name`, `location`
    

    就是这样,我们终于可以在带有横向视图的推文上使用 select。

    第 3 步和最终查询:

    SELECT t.* FROM tweets t LATERAL VIEW json_tuple(t.tweet, 'user', 'identifier' ) t1 as `user`, `identifier` LATERAL VIEW json_tuple(t1.`user`,'name', 'location') t2 as `name`, `location` where t1.`identifier`=1234 and `location` ="USA";

    有关横向视图的更多信息:LateralView 在 Json_Tuple 上:JsonTuple

    【讨论】:

    • 我不确定,如果您在 5TB 表上应用横向视图分解,选择数据将花费大量时间。我觉得可能是 reg replace 或 substring 可能更快。
    猜你喜欢
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多