Insert data when no match by update_by_query in elastic search

882 views Asked by At

I have this command that don't match any data in elastic search and I want to insert it after that.

//localhost:9200/my_index/my_topic/_update_by_query
{
    "script": {
        "source": "ctx._source.NAME = params.NAME",
        "lang": "painless",
        "params": {
            "NAME": "kevin"
        }
    },
    "query": {
        "terms": {
            "_id": [
                999
            ]
        }
    }
}

I try using upsert but it return errors Unknown key for a START_OBJECT in [upsert].

I don't want using update + doc_as_upsert cause I have a case that I will don't send id in my update query.

How can I insert this with update_by_query. Thank you.

If elastic search don't support. I think I will check condition if have id or not, and use indexAPI to create and update to update.

1

There are 1 answers

3
Val On

_update_by_query runs on existing documents contained in an existing index. What _update_by_query does is scroll over all documents in your index (that optionally match a query) and perform some logic on each of them via a script or an ingest pipeline.

Hence, logically, you cannot create/upsert data that doesn't already exist in the index. The Index API will always overwrite your document. Upsert only works with in conjunction with the _update endpoint, which is what you should probably do.