简体   繁体   English

使用TransportClient更新Java中存储在ElasticSearch中的数据

[英]Update data stored in ElasticSearch in Java with TransportClient

I'm trying to update data in Elastic Search in my Java program with TranportClient class. 我正在尝试使用TranportClient类在Java程序中更新Elastic Search中的数据。 I know I can UPDATE in this way : 我知道我可以这样更新:

   XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
       .field("source.ivarId", source.ivarId)
       .field("source.channel", source.channel)
       .field("source.bacId", source.bacId).endObject();
   UpdateResponse response = client.prepareUpdate(_index, _type, _id).setDoc(builder.string()).get();

while source is my user-defined class which contains 3 fields : ivarId , channel and bacId . source是我的用户定义类,其中包含3个字段: ivarIdchannelbacId

But I want to know is there any method that could do the same thing, but using another more efficient and easier way, so that I don't need to assign each field inside a class? 但是我想知道是否有任何方法可以做同样的事情,但是使用另一种更有效更轻松的方法,这样我就不需要在类中分配每个字段了? For example, can I do like this? 例如,我可以这样吗?

   XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
       .field("source", source).endObject();
   UpdateResponse response = client.prepareUpdate(_index, _type, _id).setDoc(builder.string()).get();

I tried the latter method, and I got this exception : 我尝试了后一种方法,但出现了这个异常:

MapperParsingException[object mapping for [source] tried to parse field [source] as object, but found a concrete value]

I'm using Java 1.8.0.121 , and both versions of ElasticSearch and TransportClient are 5.1 . 我正在使用Java 1.8.0.121ElasticSearchTransportClient的两个版本均为5.1 Thanks! 谢谢!

The answer is much more easier than I thought. 答案比我想象的要容易得多。

Gson gson = new Gson();
String sourceJsonString = gson.toJson(updateContent);
UpdateResponse response = client
    .prepareUpdate(_index, "logs", id).setDoc(sourceJsonString).get();

updateContent is the object that contained new data, just to transform it to Json string, then use that to update, done. updateContent是包含新数据的对象,只是将其转换为Json字符串,然后使用它来完成更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM