Pyspark 从结构化流中的地图数组中提取值
Pyspark Extract Values from from Array of maps in structured streaming
我有以下架构:
root
|-- sents: array (nullable = false)
| |-- element: integer (containsNull = true)
|-- metadata: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: string (valueContainsNull = true)
在 table 中它看起来像这样:
+----------+---------------------------------------------------------------------+
|sents |metadata |
+----------+---------------------------------------------------------------------+
|[1, -1, 0]|[[confidence -> 0.4991], [confidence -> 0.5378], [confidence -> 0.0]]|
+----------+---------------------------------------------------------------------+
如何从数组列中的地图列表中访问 te 值?
谢谢
这里有两个选项在 Spark 中使用 explode and transform 高阶函数。
选项 1(分解 + pyspark 访问器)
首先我们将数组的 explode
元素放入一个新列中,接下来我们使用键 metadata
访问映射以检索值:
from pyspark.sql.functions import col, explode, expr
df = spark.createDataFrame([
[[{"confidence":0.4991}, {"confidence":0.5378}, {"confidence":0.0}]]
], ["metadata"])
df.select(explode(col("metadata")).alias("metadata")) \
.select(col("metadata")["confidence"].alias("value"))
# +------+
# |value |
# +------+
# |0.4991|
# |0.5378|
# |0.0 |
# +------+
选项 2(变换 + 爆炸)
这里我们使用 transform
将地图的值提取到一个新数组中,然后我们 explode
它:
df.select(explode(expr("transform(metadata, i -> i['confidence'])")).alias("value"))
我有以下架构:
root
|-- sents: array (nullable = false)
| |-- element: integer (containsNull = true)
|-- metadata: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: string (valueContainsNull = true)
在 table 中它看起来像这样:
+----------+---------------------------------------------------------------------+
|sents |metadata |
+----------+---------------------------------------------------------------------+
|[1, -1, 0]|[[confidence -> 0.4991], [confidence -> 0.5378], [confidence -> 0.0]]|
+----------+---------------------------------------------------------------------+
如何从数组列中的地图列表中访问 te 值?
谢谢
这里有两个选项在 Spark 中使用 explode and transform 高阶函数。
选项 1(分解 + pyspark 访问器)
首先我们将数组的 explode
元素放入一个新列中,接下来我们使用键 metadata
访问映射以检索值:
from pyspark.sql.functions import col, explode, expr
df = spark.createDataFrame([
[[{"confidence":0.4991}, {"confidence":0.5378}, {"confidence":0.0}]]
], ["metadata"])
df.select(explode(col("metadata")).alias("metadata")) \
.select(col("metadata")["confidence"].alias("value"))
# +------+
# |value |
# +------+
# |0.4991|
# |0.5378|
# |0.0 |
# +------+
选项 2(变换 + 爆炸)
这里我们使用 transform
将地图的值提取到一个新数组中,然后我们 explode
它:
df.select(explode(expr("transform(metadata, i -> i['confidence'])")).alias("value"))