ElasticSearch 简单的 搜索 聚合 分析
一、 搜索
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": ,
"size":
}
查询结果中返回的字段 设置
查询结果中返回的字段 设置
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" : }
}
}
}
}
}
3、full-text search(全文检索)
GET /shop/goods/_search
{
"query" : {
"match" : {
"producer" : "xxx"
}
}
}4、phrase search(短语搜索)
短语搜索的功能和全文检索相对应,全文检索会将输入的搜索串拆解开来,去倒排索引里面去一一匹配,只要能匹配上任意一个拆解后的单词,就可以作为结果返回
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": ,
"aggs": {
"all_tags": {
"terms": { "field": "tags" }
}
}
}2、对名称中包含xxx的商品,计算每个tag下的商品数量
GET /shop/goods/_search
{
"size": ,
"query": {
"match": {
"name": "yagao"
}
},
"aggs": {
"all_tags": {
"terms": {
"field": "tags"
}
}
}
}
3、先分组,再算每组的平均值,计算每个tag下的商品的平均价格
GET /shop/goods/_search
{
"size": ,
"aggs" : {
"group_by_tags" : {
"terms" : { "field" : "tags" },
"aggs" : {
"avg_price" : {
"avg" : { "field" : "price" }
}
}
}
}
}
4、计算每个tag下的商品的平均价格,并且按照平均价格降序排序
GET /shop/goods/_search
{
"size": ,
"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"
}
}
}
}
}
}
}
} 相关推荐
另外一部分,则需要先做聚类、分类处理,将聚合出的分类结果存入ES集群的聚类索引中。数据处理层的聚合结果存入ES中的指定索引,同时将每个聚合主题相关的数据存入每个document下面的某个field下。