get json object hive 解析MongoDB json嵌套 文档数据存入hive后做字段取值

Hive是大数据生态圈的数据仓库工具。通过hive,我们可以方便地进行ETL的工作。我们之前的文章已经介绍过一些hive sql的基本操作以及具体的实例代码演示,今天我们介绍另一个场景应用,就是在hive中解析json嵌套。

一般情况下,存储json文本格式的工具是MongoDB这些nosql db, 而hive和MongoDB是可以相互做数据的传输同步的,假设从MongoDB中把数据同步到hive中,我们在hive里对数据做解析,取值的基本操作如下。

1、存入方式

MongoDB的文档数据存入hive时,尽可能把整个文档存入到一个hive表字段中(如果有业务限定或者有特定场景需要把个别字段单独提取出来除外)。

2、json示例

json数据格式
{
    "bedroom": {
        "min_value": 2,
        "max_value": 3,
        "tags": [
            {
                "id": 2,
                "name": "2居室",
                "score": 0.00055233
            },
            {
                "id": 3,
                "name": "3居室",
                "score": 0.00055233
            }
        ]
    },
    "build_type": [
        {
            "id": 1,
            "name": "板楼",
            "score": 0.00055233
        }
    ],
    "user_level": 1,
    "user_type": 2
}

这个json数据中有不同的类型的json嵌套,这一个document我们会整体存入hive的一个字段中,比如字段名我们叫做 content;而我们在hive中对json数据做解析一般会用到两个函数,分别是get_json_object和json_tuple, 这两个函数都是对json字段做解析,区别是json_tuple是可以一次提取多个json中的字段,而 get_json_object 只能提取一个字段。

直接提取普通字段或者不做深层解析

select
      get_json_object(content, '$.user_level') as level
from document

对list格式的嵌套json做解析

select pp.col,r.name, r.score
from (
      select split(regexp_replace(regexp_extract(content,
                        '^\\[(.+)\\]$',1),
             '\\}\\,\\{', '\\}\\|\\|\\{'),
       '\\|\\|'
     ) as cont
from document) ss
lateral view explode(ss.cont) pp as col 
lateral view json_tuple(ss.cont,'name','score') r as name,score;