Elasticsearch. Update, delete a document

July 9, 2016 18 Yehor Rykhnov

Elasticsearch. Part 7, update, delete a document in Elasticsearch. Previous part: Elasticsearch. Highlight search results.

Update and delete data. Change the name of the user, add a kind of passion coffe and add cars that have this member.

Update and delete data

Command:

POST /megacorp/employee/1/_update
{
    "doc" : 
    {
        "first_name" : [ "Bob" ],       
        "interests": [ "sports", "music", "coffe" ],       
        "cars": ["audi", "bmw"],    
        "views": 0
    }
}

Get data:

GET /megacorp/employee/1

Delete the document:

DELETE /megacorp/employee/1

CURL:

curl -XPOST 'localhost:9200/megacorp/employee/1/_update?pretty' -d '
{  
    "doc": 
    { 
        "first_name": "Bob" ,
        "interests": [ "sports", "music", "coffe" ], 
        "cars": ["audi", "bmw"]
    }
}'

Get data:

$curl -XGET 'http://localhost:9200/megacorp/employee/1 '

Delete the document:

curl -XDELETE 'localhost:9200/megacorp/employee/1'

PHP:

Update data:

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
            "id"    => '1',
            "index" => "megacorp",
            "type"  => "employee",
            "body"  => [
                "doc" => [
                    "first_name" => "Bob",
                    "last_name"  => "Smith",
                    "age"        => "25",
                    "about"      => 'I love to go rock climbing',
                    "interests"  => [ "sports", "music", "coffe"],
                    "cars"       => ["audi", "bmw"]
                ]
            ]        
];
try {
    $response = $client->update($params);
} catch (Exception $e) {
    var_dump($e->getMessage());
}

Delete data:

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
            "id"    => '1',
            "index" => "megacorp",
            "type"  => "employee",
        ];
try {            
    $response = $client->delete($params);        
} catch (Exception $e) {
            var_dump($e->getMessage());        
}

Yii2:

Add the record cars in the array of attributes and rules.

public function attributes() {
  return [
      "first_name",
      "last_name",
      "age" ,
      "about" ,
      "interests" , 
      "cars" ,
  ];
}

We get our employee:

$model = Megacorp::get(1);

Update data:

$model->attributes = [
            "first_name" => "Bob",
            "interests"  => [ "sports", "music", "coffe"],
            "cars"       => ["audi", "bmw"]
];
$model->save();

Display the result:

$model = Megacorp::get(1);
var_dump($model);

Delete data:

$model = Megacorp::get(10);    
$model->delete();

Additionally