Elasticsearch简单的搜索与聚合
原文链接链接: https://www.cnblogs.com/phpshen/p/8855856.html.
一、 搜索
1.DSL搜索
全部数据没有任何条件
GET /shop/goods/_search
{
"query": { "match_all": {} }
}
查询名称包含 xxx 的商品,同时按照价格降序排序
GET /shop/goods/_search
{
"query" : {
"match" : {
"name" : "xxx"
}
},
"sort": [
{ "price": "desc" }
]
}
分页查询商品 from 第几条开始 size 获取几条
GET /shop/goods/_search
{
"query" : {
"match" : {
"name" : "xxx"
}
},
"from": 1,
"size": 1
}
查询结果中返回的字段 设置
GET /shop/goods/_search
{
"query" : {
"match" : {
"name" : "xxx"
}
},
"_source": ["name", "price"]
}
2、query filter
搜索商品名称包含xxx,而且售价大于25元的商品
GET /shop/goods/_search
{
"query" : {
"bool" : {
"must" : {
"match" : {
"name" : "xxx"
}
},
"filter" : {
"range" : {
"price" : { "gt" : 25 }
}
}
}
}
}
3、full-text search(全文检索)
GET /shop/goods/_search
{
"query" : {
"match" : {
"producer" : "xxx"
}
}
}
4、phrase search(短语搜索)
GET /shop/goods/_search
{
"query" : {
"match_phrase" : {
"producer" : "xxx"
}
}
}
5、highlight search(高亮搜索结果)
高亮优化:
方式1:传统plain高亮方式。
官网明确支持,该方式匹配慢,如果出现性能问题,请考虑其他高亮方式。
方式2: postings 高亮方式。
方式3: fast-vector-highlighter 简称fvh高亮方式。
GET /shop/goods/_search
{
"query" : {
"match" : {
"producer" : "xxx"
}
},
"highlight": {
"fields" : {
"producer" : {}
}
}
}
二、 聚合、分析
5.x以后对排序,聚合这些操作用单独的数据结构(fielddata)缓存到内存里了,需要单独开启。
开启字段的fielddata
PUT /shop/_mapping/goods
{
"properties": {
"tags": {
"type": "text",
"fielddata": true
}
}
}
1、计算每个tag下的商品数量
GET /shop/goods/_search
{
"aggs": {
"group_by_tags": {
"terms": { "field": "tags" }
}
}
}
size表示不返回文档 只返回聚合分析后的结果 group_by_tags和all_tags 只是给本次聚合 起一个名字 没有功能的区别
GET /shop/goods/_search
{
"size": 0,
"aggs": {
"all_tags": {
"terms": { "field": "tags" }
}
}
}
2、对名称中包含xxx的商品,计算每个tag下的商品数量
GET /shop/goods/_search
{
"size": 0,
"query": {
"match": {
"name": "yagao"
}
},
"aggs": {
"all_tags": {
"terms": {
"field": "tags"
}
}
}
}
3、先分组,再算每组的平均值,计算每个tag下的商品的平均价格
GET /shop/goods/_search
{
"size": 0,
"aggs" : {
"group_by_tags" : {
"terms" : { "field" : "tags" },
"aggs" : {
"avg_price" : {
"avg" : { "field" : "price" }
}
}
}
}
}
4、计算每个tag下的商品的平均价格,并且按照平均价格降序排序
GET /shop/goods/_search
{
"size": 0,
"aggs" : {
"all_tags" : {
"terms" : { "field" : "tags", "order": { "avg_price": "desc" } },
"aggs" : {
"avg_price" : {
"avg" : { "field" : "price" }
}
}
}
}
}
5、按照指定的价格范围区间进行分组,然后在每组内再按照tag进行分组,最后再计算每组的平均价格
GET /shop/goods/_search
{
"size": 0,
"aggs": {
"group_by_price": {
"range": {
"field": "price",
"ranges": [
{
"from": 0,
"to": 20
},
{
"from": 20,
"to": 40
},
{
"from": 40,
"to": 50
}
]
},
"aggs": {
"group_by_tags": {
"terms": {
"field": "tags"
},
"aggs": {
"average_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
}
}