scala - 选择以特定模式开头的字段:Spark XML Parsing
问题描述
我不得不解析一些非常大的 xml 文件。我想提取这些 xml 文件中的一些字段,然后对它们执行一些工作。但是,我需要遵循一些规则,即我只能选择遵循某种模式的字段。
这是我要实现的目标的示例:
// Some made up data
val schema = new StructType()
.add("devices",
new StructType()
.add("thermostats", MapType(StringType,
new StructType()
.add("device_id", StringType)
.add("locale", StringType)
.add("E2EDK1000", StringType)
.add("E2EDK2000", StringType)
.add("E2EDK3000", StringType))))
val nestDataDS2 = Seq("""{
"devices": {
"thermostats": {
"peyiJNo0IldT2YlIVtYaGQ": {
"device_id": "peyiJNo0IldT2YlIVtYaGQ",
"locale": "en-US",
"E2EDK1000": "4.0",
"E2EDK2000": "VqFabWH21nwVyd4RWgJgNb292wa7hG_dUwo2i2SG7j3-BOLY0BA4sw",
"E2EDK3000": "Hallway Upstairs"}}}}""").toDS
val nestDF2 = spark
.read
.schema(nestSchema2)
.json(nestDataDS2.rdd)
root
|-- devices: struct (nullable = true)
| |-- thermostats: map (nullable = true)
| | |-- key: string
| | |-- value: struct (valueContainsNull = true)
| | | |-- device_id: string (nullable = true)
| | | |-- locale: string (nullable = true)
| | | |-- E2EDK1000: string (nullable = true)
| | | |-- E2EDK2000: string (nullable = true)
| | | |-- E2EDK3000: string (nullable = true)
鉴于此,我想进入值字段,所以我执行以下操作
val tmp = nestDF2.select($"devices.thermostats.value")
root
|-- value: struct (nullable = true)
| |-- device_id: string (nullable = true)
| |-- locale: string (nullable = true)
| |-- E2EDK1000: string (nullable = true)
| |-- E2EDK2000: string (nullable = true)
| |-- E2EDK3000: string (nullable = true)
这是我的问题:我想选择 value 中以以下模式 E2EDK1 开头的所有字段。但是,我坚持如何做到这一点。这是我想要的最终结果:
root
|-- E2EDK1000: string (nullable = true)
我知道我可以直接选择该字段,但在我使用的数据中,E2EDK1000 并不总是会一直存在。永远存在的是 E2EDK1。
我试过使用 startsWith() 但这似乎不起作用,例如
val tmp2 = tmp
.select($"value".getItem(_.startsWith("E2EDK1")))
解决方案
您可以使用.*
将值列的所有元素选择到单独的列中,过滤所有以开头的元素名称,E2EDK1
最后仅选择那些列,如下所示
//flattens the struct value column to separate columns
val tmp = nestDF2.select($"devices.thermostats.value.*")
//filter in the column names that starts with E2EDK1
val e2edk1Columns = tmp.columns.filter(_.startsWith("E2EDK1"))
//select only the columns that starts with E2EDK1
tmp.select(e2edk1Columns.map(col):_*)
它应该为您提供以单独列开头的value struct 列的所有元素。E2EDK1
对于您给定的示例,您应该将输出为
+---------+
|E2EDK1000|
+---------+
|null |
+---------+
root
|-- E2EDK1000: string (nullable = true)
struct
如果您愿意,可以将它们组合回
推荐阅读
- haskell - 如何在 do 表达式中返回 True 或 False - Haskell
- c++ - yaml-cpp 可以用作仅标头库吗?
- javascript - 选择数据控制名称
- typescript - 为全局创建模拟
- javascript - 如何改变鼠标点击?从左键到按下滚轮
- html - 无法在本地 Safari 上加载/播放视频
- apache-spark - spark partitionBy内存不足故障
- kdb - 将 kdb 日期时间四舍五入到最接近的偶数秒
- angularjs - Karma 单元测试 webpack:进程内存不足后返回的 API 致命错误处理程序
- javascript - 如何用javascript转换json日期记录