2017-12-07 3 views
0

저는 Spark를 처음 사용합니다. 내가 원하는 것은 중첩 된 jsons를 읽고 특정 조건에 따라 그룹화하는 것입니다. 예 : json에 도시와 우편 번호와 같은 사람의 세부 정보가있는 경우 나는 같은 도시와 우편 번호에 속한 사람들을 그룹화하고 싶습니다.집계를 위해 중첩 JSON을 읽는 방법은 무엇입니까?

나는 DataSet에 jsons를 읽을 때까지 진행되었습니다. 하지만 그룹화하는 방법을 알지 못합니다.

내 중첩 된 JSON 형식이 내가 파일에서 중첩 된 JSON을 읽고 작성한 코드입니다

{ 
    "entity": { 
    "name": "SJ", 
    "id": 31 
    }, 
    "hierarchy": { 
    "state": "TN", 
    "city": "CBE" 
    }, 
    "data": {}} 

입니다.

public void groupJsonString(SparkSession spark) { 
    Dataset<Row> studentRecordDS = spark.read() 
      .option("timestampFormat", "yyyy/MM/dd HH:mm:ss ZZ") 
      .json("/home/shiney/Documents/NGA/sparkJsonFiles/*.json"); 
    StructType st = studentRecordDS.schema(); 


    List<StructType> nestedList = new ArrayList<>(); 
    for(StructField field : st.fields()) { 
     nestedList.add((StructType)field.dataType()); 
    } 

} 

답변

2

TL (당신처럼) DR 사용 spark.read.jsonselect에서 연산자를 "결합"하였다.

(I 스칼라를 사용하고 떠나는 당신의 가정 운동 : 자바로 변환)

은 이제 당신의 샘플을 사용하자.

$ cat ../datasets/sample.json 
{ 
    "entity": { 
    "name": "SJ", 
    "id": 31 
    }, 
    "hierarchy": { 
    "state": "TN", 
    "city": "CBE" 
    }, 
    "data": {} 
} 

코드는 다음과 같을 수 있습니다 (다시 스칼라입니다).

val entities = spark 
    .read 
    .option("multiLine", true) 
    .json("../datasets/sample.json") 
scala> entities.printSchema 
root 
|-- entity: struct (nullable = true) 
| |-- id: long (nullable = true) 
| |-- name: string (nullable = true) 
|-- hierarchy: struct (nullable = true) 
| |-- city: string (nullable = true) 
| |-- state: string (nullable = true) 

는 이제 entityhierarchy 최상위 열을 평평 보자.

scala> entities.select("entity.*", "hierarchy.*").show 
+---+----+----+-----+ 
| id|name|city|state| 
+---+----+----+-----+ 
| 31| SJ| CBE| TN| 
+---+----+----+-----+ 

집계는 지금 ​​당장 생각할 필요가 없습니다.

관련 문제