在开始配置之前,首先你要先确定你在你的主机上配置了Node.js环境和Java环境,在配置了这两个环境之后,我们就可以开始接下来的步骤了
首先,我们先在项目中添加Node.js提供的的elasticsearch官方模块,称为elasticsearch,通过npm安装完成:
npm install elasticsearch --save
如果成功了,你就会在项目中发现多了一个文件夹,就是Node.js关于elasticsearch的官方模块,然后你就可以在你的脚本当中导入模块:
var elasticsearch = require('elasticsearch');
最终,你需要创建客户端来处理与弹性搜索的通讯。在这种情况下,我假设你正在运行弹性搜索的本地机器IP地址是127.0.0.1,端口是9200(默认设置):
var client = new elasticsearch.Client({
host: ES_DOMAIN,
log: 'trace'
});
然后设置elasticsearch服务器的超时时间:
client.ping({
// ping usually has a 3000ms timeout
requestTimeout: 1000
}, function (error) {
if (error) {
console.trace('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
然后再进行数据导入:
var data = {//变量可以任意设置,我是以自己项目作为例子
fileId:fieleId,
content:content,
fileName:fileName,
item:item
}
elasticsearch_node = function(data){
client.delete({
index: 'myindex',
type: 'mytype',
id: data.fileId
}, function (error, response) {
// ...
});
client.bulk({
body: [
// action description
{ index: { _index: 'myindex', _type: 'mytype', _id:data.fileId } },
// the document to index
{ content: data.content, fileName: data.fileName, fileId: data.fileId, itemId: data.item },
]
},function(err,res){
if(err){
console.log(err);
}else{
console.log(res);
return res;
}
});
}
注:有一个关注点就是_id,_id不能重复且唯一,如果你传入的数据中含有_id,如果你可以保证它唯一的情况下你可以赋值给body中的_id,如果不设置,elasticsearch会自动给你分配一个_id,但是在删除的时候,需要指定_id才能删除,具体情况视具体需求而定
更多关于elasticsearch的信息请查看官网
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31509949/viewspace-3153055/ ,如需转载,请注明出处,否则将追究法律责任。