0

我有一个类,我想使用 Scala 客户端 elastic4s 开始对 ElasticSearch 进行索引。我扩展了 DocumentMap 以允许我插入文档。String、Int 等简单值正在工作,但我似乎无法正确映射另一个类的列表。

文档看起来与此类似:

case class AThing(UserName: String, Comment: String, Time: String) 
extends  DocumentMap { 
  override def map: Map[String, Any] = Map(
   "UserName" -> UserName,
   "Comment" -> Comment,
   "Time" -> Time
  )
}

case class ThingsThatHappened(Id: String, Things: Seq[AThing] = Nil) 
extends DocumentMap {
  override def map: Map[String, Any] = Map(
    "Id" -> Id,
    "Things" ->  Things
  )
}

它将在 elasticsearch 中很好地映射 Id 字段,但是当将文档插入到 elasticsearch 中时,我得到一个看起来类似于此的不正确值:

List(AThing(id_for_the_thing,user_name_a,typed_in_comment,2015-03-12))

显然这是错误的,一旦它被插入到 elasticsearch 中,我期待与这个 JSON 结构类似的东西,例如:

"events" : [
   {
     "UserName" :"user_name_a", 
     "Comment": "typed_in_comment", 
     "Time": "2015-03-12"
   }
]

有谁知道在使用 elastic4s 索引数据时映射复杂类型数组的方法?

4

2 回答 2

1

Elastic4s 或 java 客户端(当前)不够聪明,无法确定您有嵌套的序列或数组,但如果它是嵌套的 java 映射(从 Scala 的角度来看仍然有点垃圾),它会起作用。

我认为最好的办法是使用 1.4.13 中添加的新 Indexable 类型类

所以,给定

case class AThing(UserName: String, Comment: String, Time: String) 

然后创建一个类型类并将其纳入范围

implicit object AThingIndexable extends Indexable[AThing] {
  def json = ... create json here using Jackson or similar which will handle nested sequences properly
}

然后你应该能够做到:

client.execute { index into "myIndex/AThings" source aThing }

它不像使用 DocumentMap 那样自动,但给您更多的控制权。

此处查看单元测试

于 2015-03-31T10:14:44.367 回答
0

首先你需要在 elastic4s 中创建索引。我假设你这样做了。

 client.execute {
  create index "myIndex" mappings (
    "AThings" as(
      "UserName" typed StringType,
      "Comemnt" typed StringType,
      "Time" typed StringType,
      )
    )
}

如果创建此索引,则可以直接将案例类放入其中。

val aThings = AThings("username","comment","time")
client.execute {index into "myIndex/AThings" doc aThings}
于 2015-03-30T14:13:48.390 回答