在hive中对于json的数据格式,可以使用get_json_object或json_tuple先解析然后查询。
也可以直接在hive中创建json格式的表结构,这样就可以直接查询,实战如下(hive-2.3.0版本):
1. 准备数据源
将以下内容保存为test.txt
{"student":{"name":"king","age":11,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
{"student":{"name":"wang","age":12,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
{"student":{"name":"test","age":13,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
{"student":{"name":"test2","age":14,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
{"student":{"name":"test3","age":15,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
{"student":{"name":"test4","age":16,"sex":"M"},"class":{"book":"语文","level":2,"score":80},"teacher":{"name":"t1","class":"语文"}}
2. 创建hive表
注意serde格式大小写不能写错: org.apache.hive.hcatalog.data.JsonSerDe
create external table if not exists dw_stg.student(
student map comment "学生信息",
class map comment "课程信息",
teacher map comment "授课老师信息"
)
comment "学生课程信息"
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
stored as textfile;
3. 上传数据
将test.txt上传到刚才创建的student目录
hdfs dfs -put test.txt /user/hive/warehouse/dw_stg.db/student/
4. 使用hql查询
查询所有信息记录:
记录下如果只是某个字段为json,想要获取里面的某个值怎么操作?
有这么两个函数:get_json_object()和json_tuple()
1、get_json_object()
get_json_object函数第一个参数填写json对象变量,第二个参数使用$表示json变量标识,然后用 . 或 [] 读取对象或数组;
什么意思?
1、就是这样:
select get_json_object('{"shop":{"book":[{"price":43.3,"type":"art"},{"price":30,"type":"technology"}],"clothes":{"price":19.951,"type":"shirt"}},"name":"jane","age":"23"}', '$.shop.book[0].type')
结果:
2、如果json简单,可以直接这样使用:
select get_json_object('{"name":"jack","server":"www.qq.com"}','$.server')
结果:
3、但是问题来了每次只能查一个字段
不信你可以试试:select get_json_object('{"name":"jack","server":"www.qq.com"}','$.server','$.name')
结果:
大概来说,意思是这个方法,只能接受两个参数,多的不行,那么就导致我们对同一个json数据想要查看多个值,只能多写几个get_json_object,比较麻烦,所以另一个方法就派上了用场。
4、json_tuple
使用方法:
select json_tuple('{"name":"jack","server":"www.qq.com"}','server','name')
结果:
5、但是缺点就是对于复杂的嵌套的json,就操作不了了(就是说使用不了".",“[]”这种符号来操作json对象),所以看情况选择这两个方法去使用。