Elasticsearch. Adding data (indexing)

June 13, 2016 18 Yehor Rykhnov

Elasticsearch. Part 2, the addition of data in Elasticsearch. Previous part: Elasticsearch. What is Elasticsearch and how to install it.

Example of adding data with help CURL, PHP and Yii2.

Elasticsearch. Adding data

Adding data to Elasticsearch by creating employee.

Examples:

Command:

  1. PUT /megacorp/employee/1 { "first_name" : "John",
  2. "last_name" : "Smith",
  3. "age" : 25,
  4. "about" : "I love to go rock climbing",
  5. "interests": [ "sports", "music" ]
  6. }

CURL:

  1. $curl -XPUT 'http://localhost:9200/megacorp/employee/133434 ' -d '
  2. {
  3. "name":"John",
  4. "last_name" :"Smith",
  5. "age" :25,
  6. "about" :"I love to go rock climbing",
  7. "interests": [ "sports", "music" ]
  8. }'

PHP:

To add data, you need to fill an array of three keys

index - analogue of the database name in MySQL.

type - analogue table in MySQL.

body - document. An analog recording line in MySQL table.

  1. require 'vendor/autoload.php';
  2. $client = Elasticsearch\ClientBuilder::create()->build();
  3. $params = [
  4. "index" => "megacorp",
  5. "type" => "employee",
  6. "body" => [
  7. "first_name" => "John",
  8. "last_name" => "Smith",
  9. "age" => "25",
  10. "about" => 'I love to go rock climbing',
  11. "interests" => [ "sports", "music"]
  12. ]
  13. ];
  14. $response = $client->index($params);
  15. print_r($response); // Print the result

Yii2:

In Yii2 work with elasticsearch made using Class yii\elasticsearch\ActiveRecord

Create a model. And we declare the class with the minimum parameters.

  1. use yii\elasticsearch\ActiveRecord;
  2. class Megacorp extends ActiveRecord
  3. {
  4. public static function index()
  5. {
  6. return 'megacorp';
  7. }
  8. public static function type()
  9. {
  10. return 'employee';
  11. }
  12. /**
  13. Attributes. It is important to point out. Otherwise, the data is not stored.
  14. */
  15. public function attributes()
  16. {
  17. return [
  18. "first_name",
  19. "last_name",
  20. "age" ,
  21. "about" ,
  22. "interests"
  23. ];
  24. }
  25. /**
  26. Rules. It is important to point out. Otherwise, the data is not stored.
  27. I set all the attributes of the rules as safe.
  28. You can specify any other that you need.
  29. */
  30. public function rules()
  31. {
  32. return [
  33. [$this->attributes(), 'safe']
  34. ];
  35. }
  36. }

Save data (indexing in terminology of elasticsearch)

  1. $model = new Megacorp();
  2. $model->attributes = [
  3. "first_name" => "John",
  4. "last_name" => "Smith",
  5. "age" => "25",
  6. "about" => 'I love to go rock climbing',
  7. "interests" => [ "sports", "music"]
  8. ];
  9.  
  10. $model->save();

Additionally

Previous part: Elasticsearch. What is Elasticsearch and how to install it

Next part: Example getting of data in Elasticsearch using CURL, PHP, Yii2