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 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:
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)
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.
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.