Elasticsearch. Adding data
Adding data to Elasticsearch by creating employee.
Examples:
Command:
- PUT /megacorp/employee/1 { "first_name" : "John",
- "last_name" : "Smith",
- "age" : 25,
- "about" : "I love to go rock climbing",
- "interests": [ "sports", "music" ]
- }
CURL:
- $curl -XPUT 'http://localhost:9200/megacorp/employee/133434 ' -d '
- {
- "name":"John",
- "last_name" :"Smith",
- "age" :25,
- "about" :"I love to go rock climbing",
- "interests": [ "sports", "music" ]
- }'
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.
- require 'vendor/autoload.php';
- $client = Elasticsearch\ClientBuilder::create()->build();
- $params = [
- "index" => "megacorp",
- "type" => "employee",
- "body" => [
- "first_name" => "John",
- "last_name" => "Smith",
- "age" => "25",
- "about" => 'I love to go rock climbing',
- "interests" => [ "sports", "music"]
- ]
- ];
- $response = $client->index($params);
- 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.
- use yii\elasticsearch\ActiveRecord;
- class Megacorp extends ActiveRecord
- {
- public static function index()
- {
- return 'megacorp';
- }
- public static function type()
- {
- return 'employee';
- }
- /**
- Attributes. It is important to point out. Otherwise, the data is not stored.
- */
- public function attributes()
- {
- return [
- "first_name",
- "last_name",
- "age" ,
- "about" ,
- "interests"
- ];
- }
- /**
- Rules. It is important to point out. Otherwise, the data is not stored.
- I set all the attributes of the rules as safe.
- You can specify any other that you need.
- */
- public function rules()
- {
- return [
- [$this->attributes(), 'safe']
- ];
- }
- }
Save data (indexing in terminology of elasticsearch)
- $model = new Megacorp();
- $model->attributes = [
- "first_name" => "John",
- "last_name" => "Smith",
- "age" => "25",
- "about" => 'I love to go rock climbing',
- "interests" => [ "sports", "music"]
- ];
- $model->save();
Additionally
- Elasticsearch. What is Elasticsearch and how to install it
- Example of adding data in Elasticsearch using CURL, PHP, Yii2
- Example getting of data in Elasticsearch using CURL, PHP, Yii2
- Example search in Elasticsearch using CURL, PHP, Yii2
- An example of index management in Elasticsearch using CURL, PHP, Yii2
- Parameters of fields
Previous part: Elasticsearch. What is Elasticsearch and how to install it
Next part: Example getting of data in Elasticsearch using CURL, PHP, Yii2