简体   繁体   中英

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. 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 .

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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