簡體   English   中英

如何使用 Spark/Scala 在 DataFrame 行中創建嵌套 JSON 對象的計數

[英]How to create a count of nested JSON objects in a DataFrame row using Spark/Scala

我有一列充滿 JSON 對象字符串,如下所示:

"steps":{
    "step_1":{
        "conditions":{
        "complete_by":"2022-05-17",
        "requirement":100
                     },
        "status":"eligible",
        "type":"buy"
            },
    "step_2":{
        "conditions":{
        "complete_by":"2022-05-27",
        "requirement":100
                     },
        "status":"eligible",
        "type":"buy" 
}

在步驟對象中,可以有任意數量的步驟(在合理范圍內)。

我的問題是,我將如何創建另一個 Dataframe 列來計算該行/列中每個 JSON 字符串的步數?

我正在使用 Spark/Scala,所以我使用以下內容創建了一個 UDF:

def jsonCount (col):

val jsonCountUDF = udf(jsonCount)

val stepDF = stepData.withColumn("NumberOfSteps", jsonCountUDF(col("steps")))

這就是我卡住的地方。 我想遍歷步驟列中的每一行並計算步驟對象 JSON 字符串中的步驟對象。 有沒有人有類似任務的經驗或知道簡化此任務的功能?

#make some data
str = "{\"steps\":{ \"step_1\":{\"conditions\":{ \"complete_by\":\"2022-05-17\", \"requirement\":100} }  , \"step_2\":{  \"status\":\"eligible\", \"type\":\"buy\"   }  }}"

#implement a function to return the count
def jsonCount ( jsonString ):
 import json
 json_obj = json.loads(jsonString)
 return len( json_obj["steps"] )

#define the udf
JSONCount = udf(jsonCount, IntegerType())

#create sample dataframe
df = spark.createDataFrame( [ [str] ], ["json"] )

#run udf on dataframe
df.select( df.json, JSONCount( df.json ).alias("StepCount") ).show()

+--------------------+---------+
|                json|StepCount|
+--------------------+---------+
|{"steps":{ "step_...|        2|
+--------------------+---------+

您可以嘗試選擇該子結構,然后獲取列大小。

  stepSize=  df.select($"steps.*").columns.size

然后將其添加到您的 df

df_steps = df.withColumn("NumberOfSteps",lit(stepSize))

編輯:不要為此目的使用 UDF ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM