我正在使用Java高级REST客户端。这是link to its documentation
我创建了一个客户端。
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是案例类,表示为:
Person(personId: String, name: String, address: Address)
和地址本身就是一个案例类,表示为:
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"
}
我希望我能很好地解决这个问题。任何帮助,将不胜感激。谢谢!
答案 0 :(得分:0)
你快到了。为了实现您的目标,您需要:
实际上是在Index API的页面中描述的。
将案例类序列化为JSON的方便库例如是json4s(您可以看到序列化here的一些示例)。
您的代码可能如下所示:
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)
。
希望有所帮助!