我不得不解析一些非常大的 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")))