文章目录
ElasticSearch 基本使用
上文说到 ElasticSearch的快速入门 ,本文将介绍ElasticSearch的基本使用
两种查询方式
https://www.elastic.co/guide/en/elasticsearch/reference/6.0/_the_search_api.html
REST 请求 + 搜索参数
GET /bank/_search?q=*&sort=account_number:asc
REST请求 + 请求体
DSL (Domain Specific Language)
GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "age" : "desc"},
{ "account_number": "asc"}
]
}
部分信息
QueryDSL基本语法
JSON风格得DSL语法结构
{
QUERY_NAME:{ //功能名
FIELD_NAME:{ //字段名
ARGUMENT:VALUE, //参数-值
ARGUMENT:VALUE,...
}
}
}
match全文检索
match匹配
GET /bank/_search
{
"query" : {
"match": {
"age": "22"
}
}
}
全文检索
分词全文检索,按照评分降序
GET /bank/_search
{
"query" : {
"match": {
"address": "mill lane"
}
}
}
match_phrase短语匹配
使用match时会自动分词,如果不想分词,想查询一个完整的短语就可以使用短语匹配
GET /bank/_search
{
"query": {
"match_phrase": {
"address": "mill lane"
}
}
}
multi_match多字段匹配
GET /bank/_search
{
"query": {
"multi_match": {
"query": "mill Movico",
"fields": ["address","city"]
}
}
}
注意: 查询内容会分词
bool复合查询
复合查询 可以理解为 与
, 多个查询条件都要一起满足
must,must_not,should
must: 必须满足
must_not : 必须不满足
should: 满不满足都可以,满足评分会更高
filer过滤查询
filer与must,must_not,should的不同: 是否满足都不会增加评分
GET /bank/_search
{
"query": {
"bool": {
"must": [
{"match": {
"address": "mill"
}}
],
"filter": {
"range": {
"age": {
"gte": 10,
"lte": 40
}
}
}
}
}
}
term查询
term查询与match查询类似
一般用term检索非文本的精确值
match检索文本
keyword匹配精确值
使用keyword后,文本精确值必须是匹配值才算匹配成功
GET /bank/_search
{
"query": {
"match": {
"address.keyword": "198 Mill"
}
}
}
与match_phrase短语匹配区别
GET /bank/_search
{
"query": {
"match_phrase": {
"address": "198 Mill"
}
}
}
聚合
语法格式
"aggregations" : {
"<aggregation_name>" : {
"<aggregation_type>" : {
<aggregation_body>
}
[,"meta" : { [<meta_data_body>] } ]?
[,"aggregations" : { [<sub_aggregation>]+ } ]?
}
[,"<aggregation_name_2>" : { ... } ]*
}
-
trem:对值进行分布统计
GET /bank/_search { "query": { "match_all": {} }, "aggs": { "ageaggs": { "terms": { "field": "age", "size": 10 } } } }
-
agg:对值进行平均统计
GET /bank/_search { "query": { "match_all": {} }, "aggs": { "ageaggs": { "terms": { "field": "age", "size": 10 } }, "balanceAvg":{ "avg": { "field": "balance" } } } }
嵌套聚合
如果我想在上一个聚合出的结果上进行聚合,就要使用嵌套聚合
-
对年龄聚合,统计各年龄人数,并请求这些年龄段人的平均薪资
GET /bank/_search { "query": { "match_all": {} }, "aggs": { "ageTrems": { "terms": { "field": "age", "size": 10 }, "aggs": { "balanceAvg": { "avg": { "field": "balance" } } } } } }
-
对年龄聚合,统计各年龄人数,并请求这些年龄段中M的平均薪资和F的平均薪资,以及该年龄段总体平均薪资
GET bank/_search { "query": { "match_all": {} }, "aggs": { "ageTerms": { "terms": { "field": "age", "size": 10 }, "aggs": { "genderTrems": { "terms": { "field": "gender.keyword" }, "aggs": { "balanceAvg": { "avg": { "field": "balance" } } } }, "balanceAgeAvg": { "avg": { "field": "balance" } } } } } }