> For the complete documentation index, see [llms.txt](https://learnsql.gitbook.io/lernmysql/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learnsql.gitbook.io/lernmysql/elasticsearch-and-php-and-mysql-thuc-hanh-phan-9-bulk-api.md).

# ElasticSearch & php & mysql thực hành – Phần 9 – Bulk API

## ElasticSearch & php & mysql thực hành – Phần 9 – Bulk API

[August 25, 2015](https://thinhpc86.wordpress.com/2015/08/25/elasticsearch-php-mysql-thuc-hanh-phan-9-bulk-api/) [thinhpc86](https://thinhpc86.wordpress.com/author/thinhpc86/) [Java](https://thinhpc86.wordpress.com/tag/java/), [PHP](https://thinhpc86.wordpress.com/category/php/)[ElasticSearch](https://thinhpc86.wordpress.com/tag/elasticsearch/), [Lucene](https://thinhpc86.wordpress.com/tag/lucene/), [mysql](https://thinhpc86.wordpress.com/tag/mysql/), [PHP](https://thinhpc86.wordpress.com/tag/php/)

Trong phần trước ta đã sơ lược qua cách [mapping](https://thinhpc86.wordpress.com/2015/08/17/elasticsearch-php-mysql-thuc-hanh-phan-8-mapping/).

Phần này ta sẽ thực hiện lấy dữ liệu từ mysql import vào ES bằng ngôn ngữ PHP.

Trong [phần 4](https://thinhpc86.wordpress.com/2015/06/10/elasticsearch-php-mysql-thuc-hanh-phan-4/) mình đã có đi qua api **\_bulk** để import dữ liệu vào ES. Mình nhắc lại ở đây 1 chút.

dùng **\_bulk** để xử lí hàng loạt như sau:

```
curl -XPOST 'localhost:9200/indexname/typename/_bulk?pretty' -H 'Content-Type: application/json' -d '
{"index":{"_id":"1"}}
{"title": "title 1","content":"this is content","description":"this is description","create_date":"2015-07-24 08:45:00"}
{"index":{"_id":"2"}}
{"title": "title 2","content":"this is content 2","description":"this is des 2","create_date":"2015-08-25 08:45:00"}

```

**Lưu ý:** các bạn phải lưu ý rằng dữ liệu cho api \_bulk thì **cuối mỗi dòng đều kết thúc bằng 1 ký tự xuống dòng (\n)**, **kể cả dòng cuối cùng,** nếu thiếu 1 dấu xuống dòng thì câu lệnh sẽ ko thực hiện được.

Và dưới đây là đoạn code PHP để bạn thực thiện tạo dữ liệu json theo format trên và gọi api **\_bulk:**

| 12345678910111213141516171819202122232425262728293031323334353637383940414243 | `$DbName` `=` `'dbexample';$DbUserName` `=` `'root';$DbUserPass` `=` `'';$DbOptions` `=` `array(    PDO::MYSQL_ATTR_INIT_COMMAND =>` `'SET NAMES utf8',);` `$DsnMySql` `=` `'mysql:host=localhost;dbname='` `.` `$DbName;$dbh` `=` `new` `PDO($DsnMySql,` `$DbUserName,` `$DbUserPass,` `$DbOptions);$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);$sql` `=` `"SELECT * from tableName";$query` `=` `$dbh->prepare($sql,` `array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));if` `($query->execute() === FALSE) {    throw` `new` `Exception('Failed Database execution');}` `$str` `="";while` `($row` `=` `$query->fetch(PDO::FETCH_ASSOC)) {    $item` `= [];    $id` `=` `$row['id'];    $item["title"] =` `$row['title'];    $item["content"] =` `$row['content'];    $item["description"] =` `$row['description'];    $item["create_date"] =` `$row['create_date'];    $arr` `=` `array("index"` `=>` `array("_id"` `=>` `$id));    $str` `.= json_encode($arr)."\n";    $str` `.= json_encode($item)."\n";}` `$url` `=` `"`[`http://localhost:9200/indexname/typename/_bulk?pretty`](http://localhost:9200/indexname/typename/_bulk?pretty)`";` `//call es api$ch` `= curl_init();curl_setopt($ch, CURLOPT_URL,` `$url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS,` `$str);` `ob_start();` `// prevent any output$output` `= curl_exec($ch);` `// execute the curl commandob_end_clean();` `// stop preventing outputcurl_close($ch);echo` `$output;` |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Khá đơn giản phải không.

Ngoài ra có cách thứ 2 là import dữ liệu từ file json vào ES. Bạn cần tạo ra file json với dữ liệu format như trên. Rồi dùng command line(CMD) để call api. (Mình đã thử dùng PHP nhưng chưa call được api này từ php, nhưng có thể call được từ CMD)

Bước 1: Tạo file json:

| 12345678910111213141516171819202122232425262728293031 | `$DbName` `=` `'dbexample';$DbUserName` `=` `'root';$DbUserPass` `=` `'';$DbOptions` `=` `array(    PDO::MYSQL_ATTR_INIT_COMMAND =>` `'SET NAMES utf8',);` `$DsnMySql` `=` `'mysql:host=localhost;dbname='` `.` `$DbName;$dbh` `=` `new` `PDO($DsnMySql,` `$DbUserName,` `$DbUserPass,` `$DbOptions);$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);$sql` `=` `"SELECT * from tableName";$query` `=` `$dbh->prepare($sql,` `array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));if` `($query->execute() === FALSE) {    throw` `new` `Exception('Failed Database execution');}` `$str` `="";while` `($row` `=` `$query->fetch(PDO::FETCH_ASSOC)) {    $item` `= [];    $id` `=` `$row['id'];    $item["title"] =` `$row['title'];    $item["content"] =` `$row['content'];    $item["description"] =` `$row['description'];    $item["create_date"] =` `$row['create_date'];    $arr` `=` `array("index"` `=>` `array("_id"` `=>` `$id));    $str` `.= json_encode($arr)."\n";    $str` `.= json_encode($item)."\n";}` `$tourl` `= dirname(__file__) .` `"/data.json";file_put_contents($tourl,` `$str);` |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Trên windows bạn copy file data.json này vào cùng thư mục với file elasticsearch.bat\
bạn tải curl.exe về cùng thư mục đó luôn để dùng cho tiện như hình dưới.\
[![import](https://thinhpc86.files.wordpress.com/2015/08/import.jpg?w=700)](https://thinhpc86.files.wordpress.com/2015/08/import.jpg)

Bước 2:\
Mở CMD lên và thực hiện command sau:

| 1 | `curl -XPOST` `'localhost:9200/indexname/typename/_bulk?pretty'` `--data-binary @data.json` |
| - | ------------------------------------------------------------------------------------------- |

Như vậy bạn đã biết được 2 cách import(index) dữ liệu có sẵn vào ElasticSearch. Cách thứ 2 tiện lợi hơn trong trường hợp bạn có thể backup data ra file json, lưu trữ và dùng bất cứ lúc nào, không cần đến mysql.

Chúc các bạn thực hành thành công.

Có gì thắc mắc cứ comment bên dưới mình sẽ giải đáp.
