Search code examples
elasticsearchelasticsearch-bulk-api

How to insert an element into already present list in elastic search


Say I have documents stored like below.

document 1
    {
        id : '1',
        title : "This is a test document1",
        list : ["value1" , "value2"],
        ...
    }
document 2
    {
        id : '2',
        title : "This is a test document2",
        valueList : ["value1" , "value2"],
        ...
        }

I need to add some more elements to the valueList in the documents with a list of document ids using bulk api. The resulting should look like

document 1
    {
        id : '1',
        title : "This is a test document1",
        list : ["value1" , "value2", "value3"],
        ...
    }
document 2

    {
        id : '2',
        title : "This is a test document2",
        valueList : ["value1" , "value2" , "value3"],
        ...
        }

What can I do to achieve this? I tried using the scripts but it only updates a single document.

Sorry am really new to elastic search. I could even be stupid on this question. Please forgive and make me clear with this question.


Solution

  • See Updating Document. It should be straightforward. You need to use _update and just to give you an idea, even though the documentation is nearly perfect, it could look like this:

    POST /your_index/your_type/document1/_update
    
    {
        id : '1',
        title : "This is a test document1",
        list : ["value1" , "value2", "value3"]
     }
    

    This will update document1.

    In case of bulk updates you should read Batch Processing and have a look at the Bulk API.

    From the docs:

    POST /your_index/your_type/_bulk
    { "update" : {"_id" : "document1", "_type" : "your_type", "_index" : "your_index"}}
    { "doc" : {"myfield" : "newvalue"} }
    { "update" : {"_id" : "document2", "_type" : "your_type", "_index" : "your_index"}}
    { "doc" : {"myfield" : "newvalue"} }
    

    Please note that you can just use _update for Partial Updates.

    The simplest form of the update request accepts a partial document as the doc parameter, which just gets merged with the existing document. Objects are merged together, existing scalar fields are overwritten, and new fields are added.