nodejs之elasticsearch實現分詞功能
阿新 • • 發佈:2018-12-12
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 } ] }
成功的人千方百計,失敗的人千難萬險