我已经创建了一个客户。
trait HighLevelRestClient {
def elasticSearchClient(): RestHighLevelClient = {
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", ElasticSearchPort, "http")))
}
}
索引数据时,嵌套字段将存储为String。以下代码说明了如何创建索引:
val indexRequest = new IndexRequest("my-index", "test-type").source(
"person", person,
"date", DateTime.now()
)
其中,人员是案例类,表示为:
Person(personId: String, name: String, address: Address)
而Address本身是一个case类,表示为:
Address(city: String, zip: Int)
我的应用程序要求将人员存储为键值对,以便其字段可搜索。但是,当我使用上面的代码时,它被存储为String。
{
"person" : "Person(my-id, my-name, Address(my-city, zip-value))",
"date" : "2017-12-12"
}
所需的结构是:
{
"person" : {
"personId" : "my-id",
"name" : "person-name",
"address": {
"city" : "city-name",
"zip" : 12345
}
},
"date" : "2017-12-12"
}
我希望我已经很好地解决了这个问题。任何帮助,将不胜感激。谢谢!
你快到了。为了实现您的目标,您需要:
实际上,它在Index API的页面中进行了描述。
将案例类序列化为JSON的便捷库是json4s(您可以在此处看到一些序列化的示例)。
您的代码可能如下所示:
import org.apache.http.HttpHost
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.client.{RestClient, RestHighLevelClient}
import org.elasticsearch.common.xcontent.XContentType
import org.joda.time.DateTime
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
case class Address(city: String, zip: Int)
case class Person(personId: String, name: String, address: Address)
case class Doc(person: Person, date: String)
object HighClient {
def main(args: Array[String]): Unit = {
val client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9206, "http")))
implicit val formats = Serialization.formats(NoTypeHints)
val doc = Doc(
Person("blah1", "Peter Parker", Address("New-York", 33755)),
DateTime.now().toString
)
val indexRequest = new IndexRequest("my-index", "test-type").source(
write(doc), XContentType.JSON
)
client.index(indexRequest)
client.close()
}
}
请注意在这种情况下:
new IndexRequest("my-index", "test-type").source(
write(doc), XContentType.JSON
)
此功能将用于: public IndexRequest source(String source, XContentType xContentType)
在您的情况下:
new IndexRequest("my-index", "test-type").source(
"person", person,
"date", DateTime.now()
)
它会打电话public IndexRequest source(Object... source)
。
希望有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句