DataPipeline/Hive

Apache Hive - Json 컨트롤

wave35 2023. 3. 21. 06:53

 

Hive에서 Json파일 컨트롤

 

1. get_json_object

hive 0.7.0 이하로는 아래와 같이 사용한다.

 

[ 데이터 ]

 

[ 쿼리문 ]

SELECT
  get_json_object(StudentsOneLine, '$.StudentDetails.FirstName'),
  get_json_object(StudentsOneLine, '$.StudentDetails.LastName')
FROM
  StudentsOneLine;

 

 

2. json_tuple 사용

아래와 같은 json 파일이 있다.

{
    "memberId":817090,"campaigns": [
    	{"id":"40718","amount":"10"},
        {"id":"40801","amount":"26"},
        {"id":"40584","amount":"0"},
        {"id":"40685","amount":"0"}
     ],
     "eventTime":"1604847624784",
     "createdAt":"2020-11-09:00:00:25"
 }

 

hive 0.7.0이상부터는 json_tuple함수를 이용하여 json데이터를 추출한다.

 

[ 쿼리문 ]

SELECT 
	memberid, id, amount, eventtime
from 
	tableName 
LATERAL VIEW JSON_TUPLE(campaigns) campaigns as id, amount;

 

 

3. Explode

그러나 데이터가 아래와 같이 String 타입이 아니고 Int타입 Json이라면

{
    "memberId":817090,
    "campaigns":[
        {"id":40718,"amount":10},
        {"id":40801,"amount":26},
        {"id":40584,"amount":0},
        {"id":40685,"amount":0}
    ],
    "eventTime":1604847624784,
    "createdAt":"2020-11-09:00:00:25"
}

 

아래와 같은 에러가 나타난다.

Error while compiling statement: FAILED: UDFArgumentException json_tuple()'s arguments have to be string type

그럴땐 Explode함수를 사용하여 Json을 추출한다.

 

[ 쿼리문 ]

SELECT
    memberid, ca.id, ca.amount, eventtime
from
    tablename
LATERAL VIEW EXPLODE(campaigns) campaigns as ca

 

 

[ 결과 ]

 

 

4. 사용자 지정 SerDe사용

Hive에서는 json, csv뿐 아니라 커스텀으로 만들어 SerDe를 사용할 수 있다.

 

참조 URL : https://web.archive.org/web/20190217104719/https://blogs.msdn.microsoft.com/bigdatasupport/2014/06/18/how-to-use-a-custom-json-serde-with-microsoft-azure-hdinsight/

 

How to use a Custom JSON Serde with Microsoft Azure HDInsight

I had a recent need to parse JSON files using Hive. There were a couple of options that I could use. One is using native Hive JSON function such as get_json_object and the other is to use a JSON Serde to parse JSON objects containing nested elements with

web.archive.org

 

 

5. 프로그래밍

Python, Java를 이용하여 Json파일을 컨트롤 한다.

 

참조 :

https://docs.microsoft.com/ko-kr/azure/hdinsight/hadoop/using-json-in-hive

 

Apache Hive로 JSON 분석 및 처리 - Azure HDInsight

Azure HDInsight에서 Apache Hive를 사용하여 JSON 문서를 사용하고 분석하는 방법을 알아봅니다.

learn.microsoft.com