1.安裝 egg-es
npm i egg-es --save
2.建一個Controller 做資料新增
注意 my-index-005 這是ES內的index名稱 , 假設為 my-index-005
const Controller = require('egg').Controller;
const elasticsearch = require('elasticsearch');
class EstestController extends Controller {
async add() {
var esClient = new elasticsearch.Client({
host: 127.0.0.1:9002,
log: 'info'
});
let result = await esClient.bulk({
body: [
{ index: { _index: 'my-index-005', _id: '10002245' } },
{ content: '測試寫入內容' }
]
});
this.ctx.body = result;
}
}
module.exports = EstestController;
3.資料更新
async edit() {
let result = await esClient.bulk({
body: [
{ update: { _index: 'my-index-005', _id: '10002245' } },
{ doc: { content: '更新後的內容' } },
]
});
this.ctx.body = result;
}
4.搜尋
async query() {
let result = await esClient.search({
index: 'news',
body: {
query: {
match: {
content: '欲查詢的內容'
}
}
}
});
console.log('result: ', JSON.stringify(result));
}
5.刪除
async delete() {
let result = await esClient.bulk({
body: [
{ delete: { _index: 'my-index-005', _id: '10002245' } },
]
});
}
完成便可以到kibana確認