0

我有一个嵌套的 json 数据,其中包含要提取和构造 Scala 映射的嵌套字段。

下面是示例 JSON:

"nested_field": [
  {
    "airport": "sfo",
    "score": 1.0
  },
  {
    "airport": "phx",
    "score": 1.0
  },
  {
    "airport": "sjc",
    "score": 1.0
  }
]

我想使用saveToES()并构造一个 Scala Map 将字段索引到 ES 索引中,映射如下:

 "nested_field": {
    "properties": {
      "score": {
        "type": "double"
      },
      "airport": {
        "type": "keyword",
        "ignore_above": 1024
      }
    }
  }

使用 spark.read.json("example.json") 将 json 文件读入数据帧。在这种情况下,构建 Scala Map 的正确方法是什么?

谢谢你的帮助!

4

1 回答 1

0

您可以使用以下示例代码进行操作

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods.parse



  case class AirPortScores(airport: String, score: Double)
  case class JsonRulesHandler(airports: List[AirPortScores])

  val jsonString: String = """{"airports":[{"airport":"sfo","score":1},{"airport":"phx","score":1},{"airport":"sjc","score":1}]}"""

  def loadJsonString(JsonString: String): JsonRulesHandler = {
  implicit val formats: DefaultFormats.type = org.json4s.DefaultFormats
  parse(JsonString).extract[JsonRulesHandler]
}

val parsedJson: JsonRulesHandler = loadJsonString(jsonString)
parsedJson.airports.foreach(println)//you can select parsedJson.airport or scores
//below ouput
AirPortScores(sfo,1.0)
AirPortScores(phx,1.0)
AirPortScores(sjc,1.0)
于 2019-01-03T17:45:20.610 回答