Elasticsearch学习笔记之—search
查询全部
1、/_search 所有索引,所有type下的所有数据都搜索出来
2、/index1,index2/_search 查询多个索引下的数据,示例
GET /test,.newkibana_1/_search { "query": { "match_all": {} } }
3、轻量api之1查询msg字段包含apple的记录 GET /test,.newkibana_1/_search?q=msg:apple
4、轻量api之2查询msg字段不包含apple的记录 GET /test,.newkibana_1/_search?q=-msg:apple
5、轻量api之3可以多个条件如:GET /test,.newkibana_1/_search?q=-msg:apple -name:tree 多个条件之间用空格
6、轻量api之从全部字段里进行搜索 GET /test,.newkibana_1/_search?q=-apple
7、只取某个字段的值
GET /test,.newkibana_1/_search { "query":{ "match_all":{} }, "_source":["space.name","type"] }
8、排序
GET /music/children/_search { "query":{ "match": { "name": "gymbo" } }, "sort":[{"length":"desc"}] }
9、分页
GET /music/children/_search { "query": { "match_all":{} }, "from": 10, "size": 10 }
10、数字范围过滤
GET /music/children/_search { "query":{ "bool":{ "must": [ {"match": { "name": "gymbo" }} ], "filter": {"range": { "length": { "gte": 65, "lte": 80 } }} } } }
11、全文检索 不分大小写 去倒排索引中匹配
GET /music/children/_search { "query":{ "match": { "content":"friend smile" } } }
12、短语检索 不分词,必须字段内容完全匹配
GET /music/children/_search { "query":{ "match_phrase": { "content":"friend smile" } } }
13、命中
GET /test,.newkibana_1/_search { "query":{ "multi_match":{ "query":"default", "fields":["space.name"] } }, "highlight": { "fields": { "space.name":{} } } }
14、分组求合
GET /music/children/_search { "size": 0, "aggs": { "group_by_lang": { "terms": { "field": "language" } } } }
如果聚合查询时出现如下错误提示:
"root_cause": [ { "type": "illegal_argument_exception", "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [language] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead." } ]
需要将用于分组的字段的fielddata属性设置为true
PUT /music/_mapping/children { "properties": { "language": { "type": "text", "fielddata": true } } }
15、带查询条件的分组求合
GET /music/children/_search { "size": 0, "query": { "match": { "content": "friend" } }, "aggs": { "all_languages": { "terms": { "field": "language" } } } }
16、求平均值
GET /music/children/_search { "size": 0, "aggs": { "group_by_languages": { "terms": { "field": "language" }, "aggs": { "avg_length": { "avg": { "field": "length" } } } } } }
17、分组后排序
GET /music/children/_search { "size": 0, "aggs": { "group_by_languages": { "terms": { "field": "language", "order": { "avg_length": "desc" } }, "aggs": { "avg_length": { "avg": { "field": "length" } } } } } }
18、嵌套查询,区间分组+分组统计+平均值 需求:按照指定的时长范围区间进行分组,然后在每组内再按照语种进行分组,最后再计算时长的平均值
GET /music/children/_search { "size": 0, "aggs": { "group_by_price": { "range": { "field": "length", "ranges": [ { "from": 0, "to": 60 }, { "from": 60, "to": 120 }, { "from": 120, "to": 180 } ] }, "aggs": { "group_by_languages": { "terms": { "field": "language" }, "aggs": { "average_length": { "avg": { "field": "length" } } } } } } } }