nodeJs-elasticsearch使用
本文基于内部APM项目使用总结,,
elasticsearch
版本16.1.1
。
-
安装elasticsearch
yarn add elasticsearch
或着node install elasticsearch
-
Elasticsearch 与关系型数据库比较
Elasticsearch MySQL index database 数据库 type table 表 field column 字段 - type 这里Elasticsearch有变动:www.elastic.co/guide/en/el…
基础使用
创建索引
PUT /blogs
{
"settings" : {
"number_of_shards" : 3,
"number_of_replicas" : 1
}
}
number_of_shards
定义一个索引的主分片个数,默认值是5
。这个配置在索引创建后不能修改。number_of_replicas
每个主分片的复制分片个数,默认是1
。这个配置可以随时在活跃的索引上修改。
删除索引
DELETE /my_index
删除多个索引
DELETE /index_one,index_two
DELETE /index_*
DELETE /_all
初始化客户端
const elasticsearch = require('elasticsearch')
const esHost = 'localhost:9200' // 你的es连接地址和端口
const index_name = 'mytest' // 你的index名字
var client = new elasticsearch.Client({
host: esHost,
log: 'trace'
})
-
host
: 你的es连接地址和端口 -
log
: 将日志信息显示在控制台,默认level:"console"// 将日志信息写入文件中 log: { type:'file', level:"trace", path:"url" }
// 设置不同等级输出到不同的地方 log: [ { type:'console', level: 'error' }, { type: 'file', level: 'trace', path: 'url' } ]
### create
> **创建时如果index 和type不存在会自动创建,index,type相同时id重复时插入失败**
```js
const create = async ({
index = index_name,
type,
body
}) => {
const id = uuid.v1()
let resp
try {
resp = client.create({
index,
type,
id,
body
})
} catch (error) {
resp = null
}
return resp
}
-
index
你的索引名称 -
type
你的类型名称 -
body
: 你的数据,json对象如:{ first_name: 'Jane', last_name: 'Smith', age: 32, about: 'I like to collect rock albums', interests: ['music'] }
deleteById
根据Id 删除index下某个type的数据
const deleteById = async ({ index = index_name, type, id}) => {
let resp
try {
resp = await client.delete({
index,
type,
id
})
} catch (error) {
resp = null
}
return resp
}
deleteByQuery
根据查询条件删除
const deleteByQuery = async ({index = index_name, body}) =>{
let resp
try {
resp = await client.deleteByQuery({
index,
body
})
} catch (error) {
resp = null
}
return resp;
}
-
body
格式 (DSL 语法):// 删除全部 { query:{ match_all: {} } } // 按年龄删除 { query:{ match: { age: 25 } } }
search
const search = async (filter) => {
let resp
try {
resp = await client.search(filter)
} catch (error) {
resp = null
}
return resp
}
-
filter格式
{ index: "mydatabase", //q:"title:test2"//使用简单的查询字符串查询进行搜索 body: { "query": { "bool": { "must": [{ "term": { "title": "hasprice" } }] } } }, "from": 0, "size": 10, "sort": ["price:desc"] //按price降序排序 }
-
GET /_search node js 中查询语法实例
{
index:'mydatabase',
body: {
query: {
bool: {
must: [
{
match: {
platform: 'APP'
}
},
{
match: {
env: 'dev'
}
},
{
range: {
created_at: {
gte: '2019-06-14T01:21:06.599Z',
lt: '2019-06-17T01:21:06.599Z'
}
}
}
]
}
},
from: 0,
size: 10,
sort: [{
created_at: {
order: 'desc'
}
}]
}
}