Ashish Tiwari
Ashish Tiwari

Reputation: 2277

_update_by_query in elasticserach-php client

I am using elasticsearch 6.2 with elasticsearch-php 6.0 client. There is situation i got stuck. I need to update field userid = 987 where userid = 123. I went through update API, Here in every query we need to pass document ID in API (like POST test/_doc/1/_update). First i need to fetch _id and then i have to make update query with POST test/_doc/{_id}/_update


It won't possible to every time produce _id. It didn't help me.
I found another option to use _update_by_query. In which i got success by using following API:

curl -XPOST 'localhost:9200/my_index/my_type/_update_by_query?pretty' -H 'Content-Type: application/json' -d '
{
   "query":{
      "term":{
         "userid":123
      }
   },
   "script":{
      "lang":"painless",
      "inline":"ctx._source.userid = params.value",
      "params":{
         "value":987
      }
   }
}'

I am not finding any reference which shows how i can use _update_by_query with elasticserach-php client. Plus let me know if you guyz have better way to tackle this. Thanks!

Upvotes: 1

Views: 1084

Answers (1)

Ashish Tiwari
Ashish Tiwari

Reputation: 2277

I got solution So i would like to share:

$client = \Elasticsearch\ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$update = [
    'index'     => 'my_index',
    'type'      => 'my_type',
    'conflicts' => 'proceed',
    'body' => [
        'query' => [
            'term' => [
                    "userid" => 987
            ]
        ],
        'script' => [
            'lang' => 'painless',
            'inline' => 'ctx._source.userid = params.userid',
                'params' => [
                    'userid' => 123
                ]
            ]
    ]
];
$results = $client->updateByQuery($update);

It solve my problem. I think elasticserach should document this.

Upvotes: 1

Related Questions