gpt4 book ai didi

elasticsearch - 如何在Elasticsearch中存储嵌套字段

转载 作者:行者123 更新时间:2023-12-02 22:36:58 25 4
gpt4 key购买 nike

我正在使用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(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"
}

我希望我已经很好地解决了这个问题。任何帮助,将不胜感激。谢谢!

最佳答案

你快到了。为了实现您的目标,您需要:

  • 在您身边将对象序列化为JSON
  • 指定请求的内容类型

  • 它实际上在 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)

    希望有帮助!

    关于elasticsearch - 如何在Elasticsearch中存储嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767429/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com