Reputation: 4147
I am attempting to perform an Upsert on my ES system. When I run this code below:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(m);
String id = m.getId();
IndexRequest indexRequest = new IndexRequest("mediaitems", "mediaitem", m.getId())
.source(json);
UpdateRequest updateRequest =
new UpdateRequest("mediaitems", "mediaitem", m.getId()).upsert(indexRequest);
client.update(updateRequest).get(); //Throws error here
it throws and error of
"java.util.concurrent.ExecutionException:
org.elasticsearch.action.ActionRequestValidationException: Validation
Failed: 1: script or doc is missing;"
When I comment out the UpdateRequest code, and go with a plain insert, it behaves correctly.
What is going on here? I'm doing this because I want to avoid having to read all the documents that might exist on ES and then undergo an Insert-or-Update cycle.
Any help on what the problem might be is greatly appreciated.
Upvotes: 6
Views: 7966
Reputation: 1
The following code should work without throwing exception.
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(m);
String id = m.getId();
UpdateRequest updateRequest =
new UpdateRequest("mediaitems", "mediaitem", m.getId())
.doc(m).docAsUpsert(true); //assign doc
client.update(updateRequest).get();
Upvotes: 0
Reputation: 1343
could be useful. I faced this issue and fixed for self. Landed here, thought of sharing.
Similar to above, except IndexRequest and docAsUpsert (updates doc if exists, otherwise creates one). Also creates Index for the firstime if it isn't there.
byte[] bytes = mapper.writeValueAsBytes(datum);
UpdateRequest updateRequest = new UpdateRequest(topicName, "_doc", datum.getAccount_name()).doc(bytes, XContentType.JSON);
bulkProcessor.add(updateRequest);
//or
bulkProcessor.add(updateRequest.docAsUpsert(true));
Upvotes: 2
Reputation: 4147
This is the correct version i.e doesn't throw errors, of the code:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(m);
String id = m.getId();
IndexRequest indexRequest = new IndexRequest("mediaitems", "mediaitem", m.getId())
.source(json);
UpdateRequest updateRequest =
new UpdateRequest("mediaitems", "mediaitem", m.getId()).upsert(indexRequest);
//Fix is the line below
updateRequest.doc(indexRequest);
client.update(updateRequest).get();
Once I added the "updateRequest.doc" line from @alfasin suggestion it worked like a charm.
Upvotes: 7