前言:
ElasticSearch 是一个高可用开源全文检索和分析组件。提供存储服务,搜索服务,大数据准实时分析等。一般用于提供一些提供复杂搜索的应用。简称:ES
本地安装ElasticSearch(以mac为例)
1.安装
brew install elasticsearch
2.运行
brew services start elasticsearch
3.停止
brew services stop elasticsearch
4.重新运行
brew services restart elasticsearch
ElasticSearch各种查询关键字
trem 过滤
term主要用于精确匹配哪些值,比如数字,日期,布尔值或not_analyzed 的字符串(未经分析的文本数据类型):
例子:
query: {
term: {age: 30}
}
terms 过滤
terms 跟 term 有点类似,但 terms 允许指定多个匹配条件。 如果某个字段指定了多个值,那么文档需要一起去做匹配:
例子:
query: {
terms: {incident: ["点击确认按钮", "点击取消按钮]}
}
range过滤
range过滤允许我们按照指定的范围查找一批数据
例子:
query: {
range: {
age: {
gte: 18,
lt: 21
}
}
}
gt: 大于
gte: 大于等于
lt: 小于
lte: 小于等于
请求页面耗时大于1秒的数据,upstream_response_time是nginx日志中的耗时
query: {
range: {
upstream_response_time: {
gt: 1
}
}
}
exists过滤
用于查找文档中是否含有或没有某个字段
例子:
query: {
exists: {
field: "city"
}
}
bool 过滤
可以用来合并多个过滤条件查询结果的布尔逻辑,包含以下操作符
must: 多个查询条件的完全匹配,相当于and
must_not: 多个查询条件的相反匹配,相当于not
should: 至少有一个查询条件匹配,相当于or
例子:
query: {
bool:{
must: [
{term: {age: 30}},
{term: { id: "3"} }
],
must_not: {term: {id:'3' }},
should: [
{ term: { age: 30 }},
{ term: { id: 7 }}
]
}
}
match_all 查询
可以查询到所有文档
例子:
query: {
match_all: {}
}
match 查询
match查询只能就指定某个确切的值进行搜索
是一个标准查询,全局查询还是精准查询都要用到
如果使用match查询一个全文本字段,它会在真正查询之前用分析器先分析match一下查询字符
例子:
match:{
city: "北京"
}
如果用match下指定了一个确切的值,在遇到数字,日期,布尔值或者not_analyzed的字符串时,它将为你搜索你给定的值
做精确匹配搜索时,最好用过滤语句,因为过滤语句可以缓存数据
multi_match查询
multi_match 查询允许在match的基础上同时搜索多个字段,在多个字段中同时查一个
例子:
query: {
multi_match: {
query: '北京', //值
ields: [ 'city','province' ] //字段
}
}
1.项目中安装依赖elasticsearch
npm install elasticsearch
或
brew install elasticsearch
2.新建文件search.js
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
host: 'ES服务器地址IP加端口',
log: 'error'
});
const search = function search(index, body) {
return client.search({index: index, body: body});
};
module.exports = function searchTerm(data) {
let body = {
size: 10, // 一次请求几条
from: 0, // 分页 从第几条开始
sort: { "timestamp": { "order": "desc" }}, //根据触发时间倒序排序
query: {
bool: {
must: [
{
wildcard: {
incident: "test*", //模糊查询 incident中含有test的数据 *
}
}
],
must_not: [
{
term: {
parameData: "[]", //parameData不是'[]'的数据
}
}
],
},
}
};
return new Promise((resolve, reject) => {
search(' 查询文件名称', body)
.then(results => {
console.log(`found ${results.hits.total} items in ${results.took}ms`);
if (results.hits.total > 0) console.log(`returned twitters:`);
let obj ={
'total': results.hits.total, // 满足条件的总条数
'data': [],
}
let arr = [];
results.hits.hits.forEach((hit,index) =>{
obj.data.push(hit._source)
});
resolve(obj);
})
.catch(error => {
console.log(error)
reject(error)
});
})
};
以上内容总结参考于:
Elasticsearch:应用Nodejs来访问Elasticsearc https://blog.csdn.net/UbuntuTouch/article/details/100112283
ElasticSearch各种查询关键字的区别
http://www.voidcn.com/article/p-pzvxfcrh-bqu.html