首先区分下match,match_phrase,term, 参考:https://zhuanlan.zhihu.com/p/592767668?utm_id=0
示例:请求地址为http://127.0.0.1:9200/students/_search,请求体为:
{
"query": {
"match_all": {}
},
"from": 0,
"size": 2,
"_source": [
"姓名",
"年级",
"班级"
],
"sort": {
"班级": {
"order": "desc"
}
}
}
查询5年级的学生,请求body:
{
"query": {
"match": {
"年级":5
}
}
}
查询5年级2班的学生,请求body:
{
"query": {
"bool": {
"must": [
{
"match": {
"年级": 5
}
},
{
"match": {
"班级": 2
}
}
]
}
}
}
查找1班和2班的学生:
{
"query": {
"bool": {
"should": [
{
"match": {
"班级": 1
}
},
{
"match": {
"班级": 2
}
}
]
}
}
}
must表示多个条件同时满足,should表示至少匹配一个条件,filter表示过滤查询;范围使用range匹配(和match,match_all相同,指定具体条件)。
例如查询5年级1班和2班的学生:
{
"query": {
"bool": {
"must": [
{
"match": {
"年级": 5
}
}
],
"filter": {
"range": {
"班级": {
"gte": 1,
"lte": 2
}
}
}
}
}
}
{
"aggs": {
"班级分组": {
"terms": {
"field": "班级"
}
}
}
}
更多的时候,我们只想要分组统计,不需要查询原始数据,可以设置查询size为0
{
"aggs": {
"班级分组": {
"terms": {
"field": "班级"
}
}
},
"size": 0
}