前言
本節只是嘗試使用nodejs中的elasticsearch模塊實現elasticsearch在node環境下的基本增刪改查。
具體方法詳情可查看官網JavaScript API:https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
代碼
var elasticsearch=require('elasticsearch');
var client=new elasticsearch.Client({
host:"localhost:9200",
//將日誌信息顯示在控制檯,默認level:"console"
log:"trace",
//將日誌信息寫入文件中
// log:{
// type:'file',
// level:"trace",
// path:"url"
// }
//設置不同等級輸出到不同的地方
// log:[
// {
// type:'console',
// level:"error",
// },
// {
// type:"file",
// level:"trace",
// path:"url"
// }
// ]
});
//一次性執行多個命令
async function bulk(){
let resp;
try{
resp=await client.bulk({
body: [
// action description
{ index: { _index: 'myindex', _type: 'mytype', _id: 1 } },
// the document to index
{ title: 'foo' },
// action description
{ update: { _index: 'myindex', _type: 'mytype', _id: 2 } },
// the document to update
{ doc: { title: 'foo' } },
// action description
{ delete: { _index: 'myindex', _type: 'mytype', _id: 3 } },
// no document needed for this delete
]
});
}catch(e){
resp=null;
}
return resp;
}
//獲取符合條件的數量
async function count(index_name){
let resp ;
try{
resp= await client.count({
index: index_name,
// body: {
// query: {
// filtered: {
// filter: {
// terms: {
// title: ['foo']
// }
// }
// }
// }
// }
});
}catch(e){
resp=null;
}
return resp;
}
async function create(){//index,type相同時id重複時插入失敗
let resp;
try{
resp=await client.create({
index: 'myindex',
type: 'mytype',
id: '2',
body: {
title: 'Test 1',
tags: ['y', 'z'],
published: true,
published_at: '2013-01-01',
counter: 1
}
});
}catch(e){
resp=null;
}
return resp;
}
async function deleteById(index,type,id){//刪除指定的文檔
let resp;
try{
resp=await client.delete({
index: index,
type: type,
id: id
});
}catch(e){
resp=null;
}
return resp;
}
async function deleteByQuery(){
let resp;
try{
resp=await client.deleteByQuery({
index: 'myindex',
body: {
query: {
term: { published: true }
}
}
});
}catch(e){
resp=null;
}
return resp;
}
//判斷某索引是否存在
async function exists(){
let resp;
try{
resp=await client.exists({
index: 'mydatabase',
type: 'mytable',
id: 1543237871246
});
}catch(e){
resp=null;
}
return resp;
}
//查詢某索引的詳細信息介紹
async function explain(){
let resp;
try{
resp = await client.explain({
index: 'mydatabase',
type: 'mytable',
id: 1543237871246,
body: {
query: {
match: { published: true }
}
}
});
}catch(e){
resp=null;
}
return resp;
}
//獲取查詢文檔的信息
async function get(){
let resp;
try{
resp = await client.get({
index: 'mydatabase',
type: 'mytable',
id:1543237871246
});
}catch(e){
resp=null;
}
return resp;
}
//根據索引index和類型type和id獲取對象的源==相當於get()方法返回的對象中的_source字段
async function getSource(){
let resp;
try{
resp=await client.getSource({
index:"mydatabase",
type:"mytable",
id:1543237871246
});
}catch(e){
resp=null;
}
return resp;
}
//添加或者更新文檔
/**
* 將類型化JSON文檔存儲在索引中,
* 使其可搜索。當id參數未設置時,
* 將自動生成唯一的id。
* 當您指定一個id時,要麼創建一個新文檔,
* 要麼更新一個現有文檔
*/
async function index(){
let resp;
try{
resp=await client.index({
index:"mydatabase",
type:"mytable",
id:1543237871252,
body:{
title:"hasprice",
tags:["index1","index2"],
published:true,
price:30
}
});
}catch(e){
resp=null;
}
return resp;
}
/**
* 從當前集羣獲取基本信息
*/
async function info(){
let resp;
try{
resp=await client.info();
}catch(e){
resp=null;
}
return resp;
}
/**
* 根據索引、類型(可選)和id獲取多個文檔。
* mget所需的主體可以採用兩種形式:
* 文檔位置數組,或文檔id數組。
*/
async function mget(){
let resp;
try{
resp=await client.mget({
body:{
docs:[//位置數組
{_index:"mydatabase",_type:"mytable",_id:1543237871246},
{_index:"mydatabase",_type:"mytable",_id:1543237871247}
]
//ids:[1,2,3]//文檔id數組
}
})
}catch(e){
resp=null;
}
return resp;
}
/**
* 在同一個請求中執行多個搜索請求
*/
async function msearch(){
let resp;
try{
resp=await client.msearch({
body:[
//匹配所有索引和類型上的所有查詢
/*{},
{
query:{
match_all:{}
}
}*/
//在index和type的查詢條件下查詢
/*{index:'mydatabase',type:"mytable"},
{query:{query_string:{query:'test 1'}}}*/
//resp.responses[0].hits.hits[0]._source獲取其內容
]
});
}catch(e){
resp=null;
}
return resp;
}
async function search(){//resp.hits.hits[0]._source
let resp;
try{
resp=await client.search({
index:"mydatabase",
//q:"title:test2"//使用簡單的查詢字符串查詢進行搜索
body:{
"query":{
"bool":{
"must":[
{
"term":{
"title":"hasprice"
}
}
]
}
}
},
"from":0,
"size":10,
"sort":["price:desc"]//按price降序排序
});
}catch(e){
resp=null;
}
return resp;
}
async function searchTemplate(){
let resp;
try{
resp=await client.searchTemplate({
index:"mydatabase",
body:{
"source":{
"query":{
"match":{
"{{name}}":"{{value}}"
}
},
size:5//顯示查詢的數組的長度
},
params:{
"name":"tag",
"value":"1"
}
}
})
}catch(e){
resp=null;
}
return resp
}
/**
* 更新文檔的部分內容。所需的body參數可以包含以下兩種情況之一:
* 將與現有文檔合併的部分文檔。
* 更新文檔內容的腳本
*/
async function update(){
let resp;
let params={tags:'tag1'}
try{
resp=await client.update({
index:'mydatabase',
type:"mytable",
id:1543237871247,
body:{
//將部分文檔放在“doc”屬性下
// doc:{
// title:"updated"
// }
//使用腳本向文檔標記屬性添加標記,1543237871248 存在,會在tag的基礎上變化
//script:`ctx._source.tag =1`,
//script:`ctx._source.tag += ctx._source.tag`,
//script:`ctx._source.tag += "${params.tags}"`
//當文檔不存在時,將文檔計數器增加1或初始化它 1543237871249爲不存在的,當執行此語句時會初始化tag=1
// script:'ctx._source.tag+=1',
// upsert:{
// tag:1
// }
//如果你想讓你的腳本運行,不管文檔是否存在。腳本處理初始化文檔,而不是upsert元素——然後將scripted_upsert設置爲true
/*"scripted_upsert":true,
"script":{
"source":"ctx._source.tag=params.tag",
"params":{
"tag":"haha"//此時如果文檔不存在,會初始化爲haha而不是1
}
},
"upsert":{
tag:"1"
}*/
//可以讀取參數的寫法
// script:{
// "source":"ctx._source.tag+=params.count",
// "lang":"painless",
// "params":{
// "count":4
// }
// }
//移除tag屬性
// script:{
// "source":"ctx._source.remove('tag')"
// }
//可用doc來取代upsert功能初始化tag的值
/*"doc":{
"tag":"doc"
},
"doc_as_upsert":true*/
//根據query修改符合指定條件的修改
/*"script":{
"source":"ctx._source.tag=1",
"lang":"painless"
},
"query":{
"term":{
"title":"test2"
}
}*/
//source 也可以用if語句
"script":{
"source":"if(ctx._source.tag==-1){ctx._source.tag-=1}else{ctx._source.tag+=1}",
"lang":"painless"
}
}
})
}catch(e){
resp=null;
}
return resp;
}
(async function(){
let resp=await search();
console.log(resp.hits.hits)
})();
上文一些方法只是初步的功能測試,如果想達到實際使用的要求,例如搜索功能,處理人類語言(分詞,分析)等可以參考官網的權威指南和api:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html。
後續會更新elasticsearch在實際應用中的使用。