结果文档缺少字段时的 Elastic4s 搜索案例 class 示例错误

Elastic4s search case class example errors when result document is missing a field

我一直在使用 Elastic4s 手册中的这个示例。它工作正常,直到它尝试检索没有在案例 class 中指定的字段的文档。

在手册中的这个例子中,假设一个结果只有 name 并且缺少 location 字段。它会产生这个错误:

java.util.NoSuchElementException: key not found: location

我正在寻找一种处理具有不同字段的搜索结果的好方法。

代码示例:

case class Character(name: String, location: String)

implicit object CharacterHitAs extends HitAs[Character] {
  override def as(hit: RichSearchHit): Character = {
Character(hit.sourceAsMap("name").toString, hit.sourceAsMap("location").toString) }}

val resp = client.execute {
search in "gameofthrones" / "characters" query "kings landing"
}.await

val characters :Seq[Character] = resp.as[Character]

开发带有可选参数的case class时,使用Option:

case class Character(name: String, location: Option[String])

Character("Tyrion Lannister", None)

然后你所要做的就是修改你的数据提取器以传递一个None选项,如果它没有找到数据:

val tyrion = Map("location" -> "King's Landing", "name" -> "Cersei Lannister")
val cersei = Map("father" -> "Tywin Lannister?", "name" -> "Cersei Lannister")
val jaime = Map("father" -> "Tywin Lannister", "location" -> "Tower of the Hand")
val characters = List(tyrion, cersei, jaime)

case class Character(name: String, location: Option[String])

characters.map(x => Character(x.getOrElse("name", "A CHARACTER HAS NO NAME"), x.get("location")))

characters.map(...)的结果是这样的:

res0: List[Character] = List(
        Character(Cersei Lannister,Some(King's Landing)), 
        Character(Cersei Lannister,None), 
        Character(A CHARACTER HAS NO NAME NAME,Some(Tower of the Hand)))

根据 RichSearchHit 的源代码,sourceAsMap 应该 return 一个 Map 对象:

def sourceAsMap: Map[String, AnyRef] = if (java.sourceAsMap == null) Map.empty else java.sourceAsMap.asScala.toMap

鉴于您使用的是 Map shorthand,您应该能够将代码转换为:

case class Character(name: String, location: Option[String])

implicit object CharacterHitAs extends HitAs[Character] {
  override def as(hit: RichSearchHit): Character = {
Character(hit.sourceAsMap.getOrElse("name", "A CHARACTER HAS NO NAME"), hit.sourceAsMap.get("location")) }}