如何从 RDD[String] 创建特定字段的 hashMap?

How to create a hashMap of particular fields from RDD[String]?

如何从 RDD[String] 创建特定字段的 hashMap?

  {
    count: 1,
    itemId: "1122334",
    country: {
        code: {
            preferred: "USA"
        },
        name: {
            preferred: "America"
        }
    },
    states: "50",
    self: {
        otherInfo: [

        ],
        preferred: "National Parks"
    },
    Rating: 4

    }

Ho do I get a hashmap maps which have {itemid , self.preferred} :

itemId : 1122334  self.preferred : "National Parks"
itemId : 1144444  self.preferred : "State Parks"
....

我试过了,它有效但效率不高,因为我正在转换为 JSON Obj 并进行解析:

 val filteredMappingsList = countryMapping.filter(x=> {
    val jsonObj = new JSONObject(x)
    jsonObj.has("itemId") && jsonObj.get("itemId").toString.startsWith("11")

})

val finalMapping = filteredMappingsList.map(x=>{
    val jsonObj = new JSONObject(x);
    val itemId = jsonObj.get("itemId").toString()
    val preferred = jsonObj.getJSONObject("self").get("preferred ").toString()
    (itemId, preferred)
}).collectAsMap

还有其他有效的方法吗?

使用众多 JSON 库之一来解析您的数据可能仍然是您的最佳选择。但是,看起来您正在将字符串解析为 JSON 两次,一次在过滤器中,一次在地图中。我不确定这是否是它实际执行的方式。但考虑只解析一次:

val result = countryMapping.map(x => newJSONObject(x)).
               filter(jsonObj => ...).
               map{jsonObj =>
                 ...
                 (itemId, preferred)
                 }.collectAsMap