版权声明:转载请注明出处 https://blog.csdn.net/wushichao0325/article/details/84858429
nodejs之elasticsearch实现分词功能
一:首先安装ik分词器
具体安装步骤可参考我之前的文章:https://blog.csdn.net/wushichao0325/article/details/84826073
二:在nodejs中的使用
1.首先npm install 安装elasticsearch模块
npm install elasticsearch --save
2.在nodejs代码中创建连接
var elasticsearch=require('elasticsearch');
var client=new elasticsearch.Client({
host:"**.**.***.**:9200",
//将日志信息显示在控制台,默认level:"console"
log:"trace",
//将日志信息写入文件中
// log:{
// type:'file',
// level:"trace",
// path:"url"
// }
//设置不同等级输出到不同的地方
// log:[
// {
// type:'console',
// level:"error",
// },
// {
// type:"file",
// level:"trace",
// path:"url"
// }
// ]
});
3.使用elasticsearch的JavaScript api中的indices里的analyze函数实现
async function analyze(){
let resp;
try{
resp=await client.indices.analyze({
body:{
"analyzer":'ik_smart',//ik_max_word两种不同的分词形式,后者会把所有可能都列举出来
"text":["中华人民共和国是我们的祖国"]
}
});
}catch(e){
resp=null;
}
return resp;
}
(async function(){
let resp=await analyze();
console.log(resp)
})();
以上代码的打印信息如下:
"ik_smart":
{ tokens:
[ { token: '中华人民共和国',
start_offset: 0,
end_offset: 7,
type: 'CN_WORD',
position: 0 },
{ token: '是',
start_offset: 7,
end_offset: 8,
type: 'CN_CHAR',
position: 1 },
{ token: '我们',
start_offset: 8,
end_offset: 10,
type: 'CN_WORD',
position: 2 },
{ token: '的',
start_offset: 10,
end_offset: 11,
type: 'CN_CHAR',
position: 3 },
{ token: '祖国',
start_offset: 11,
end_offset: 13,
type: 'CN_WORD',
position: 4 } ] }
"ik_max_word":
{ tokens:
[ { token: '中华人民共和国',
start_offset: 0,
end_offset: 7,
type: 'CN_WORD',
position: 0 },
{ token: '中华人民',
start_offset: 0,
end_offset: 4,
type: 'CN_WORD',
position: 1 },
{ token: '中华',
start_offset: 0,
end_offset: 2,
type: 'CN_WORD',
position: 2 },
{ token: '华人',
start_offset: 1,
end_offset: 3,
type: 'CN_WORD',
position: 3 },
{ token: '人民共和国',
start_offset: 2,
end_offset: 7,
type: 'CN_WORD',
position: 4 },
{ token: '人民',
start_offset: 2,
end_offset: 4,
type: 'CN_WORD',
position: 5 },
{ token: '共和国',
start_offset: 4,
end_offset: 7,
type: 'CN_WORD',
position: 6 },
{ token: '共和',
start_offset: 4,
end_offset: 6,
type: 'CN_WORD',
position: 7 },
{ token: '国是',
start_offset: 6,
end_offset: 8,
type: 'CN_WORD',
position: 8 },
{ token: '我们',
start_offset: 8,
end_offset: 10,
type: 'CN_WORD',
position: 9 },
{ token: '的',
start_offset: 10,
end_offset: 11,
type: 'CN_CHAR',
position: 10 },
{ token: '祖国',
start_offset: 11,
end_offset: 13,
type: 'CN_WORD',
position: 11 } ] }
成功的人千方百计,失败的人千难万险