Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add more documents in already existing elasticsearch index using java API?

I have created an index and added a document using java Index API.

client.prepareIndex("details", "Key", i).setSource(putJsonDocumentString(Key, Value)).execute().actionGet();

This worked fine. Index was created and document was indexed properly. Now, I need to add another document "Keys2" in this same index. So, I did this,

client.prepareUpdate("details", "Keys2", i).setScriptParams(putJsonDocumentString(Key, Value)).execute().actionGet();

But, it's not getting added to the above index. I don't want to use Bulk API (I kept getting ClusterBlockedException, which never resolved, plus I don't have much data either) I couldn't find any sample program doing the same thing.

The exception is:

ActionRequestValidationException: Validation Failed: 1: script or doc is missing

How do I resolve this?

The method putJsonDocumentString() returns a Map<string, Object> which should work with setScriptParams(), right?

like image 663
user270386 Avatar asked Oct 31 '22 00:10

user270386


1 Answers

If I understand well, you want to add another document in the same index.

In this case, this is quite simple : you can use the same API as the first document, but with related parameters:

client.prepareIndex("details", <type_name>, <id>).setSource(putJsonDocumentString(Key, Value)).execute().actionGet();

with and placeholders of the real value of your 2nd document. From what you described, Key2 is the id, and not the type of your document.

If you are confused about the index, type and document concepts, check the basic description from the documentation.

The prepareIndex API add (or update) a document to an index. In your case, if you don't have previously created the index and type, ElasticSearch will create it on-the-fly with default parameters.

The prepareUpdate API is used to update existing documents, not to add new documents to an existing index. From documentation :

The update API allows to update a document based on a script provided.

which explains the error message you have.

like image 58
ThomasC Avatar answered Nov 15 '22 05:11

ThomasC