过滤
| match_all | 全部匹配,不做过滤,默认 |
| term | 精确匹配 |
| terms | 精确匹配多个词 |
| range | 范围匹配 |
| exists | 文档包含某属性 |
| missing | 文档不包含某属性 |
| bool | 多个过滤条件的组合 |
其中,对于bool过滤,可以有下面的组合条件:
| must | 多个查询条件的完全匹配,相当于 and。 |
| must_not | 多个查询条件的相反匹配,相当于 not。 |
| should | 至少有一个查询条件匹配, 相当于 or。 |
查询
| match_all | 全部匹配,默认 |
| match | 首先对查询条件进行分词,然后用TF/IDF评分 |
| multi_match | 与match类似,但可以用多个条件 |
| bool | 多个条件的组合查询 |
其中,对于bool查询,可以有下面的组合条件:
| must | 多个查询条件的完全匹配,相当于 and。 |
| must_not | 多个查询条件的相反匹配,相当于 not。 |
| should | 至少有一个查询条件匹配, 相当于 or。 |
#查询性别为男,年龄不是25,家庭住址最好有魔都两个字的记录
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"bool": {
"must": {
"term": {
"性别": "男"
}
},
"must_not": {
"match": {
"年龄": "25"
}
},
"should": {
"match": {
"家庭住址": "魔都"
}
}
}
}
}'
#查询注册时间从2015-04-01到2016-04-01的用户
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"bool": {
"must": {
"range": {
"注册时间": {
"gte": "2015-04-01 00:00:00",
"lt": "2016-04-01 00:00:00"
}
}
}
}
}
}'
#查询没有年龄字段的记录
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"bool": {
"must": {
"missing": {
"field": "年龄"
}
}
}
}
}'
#查询家庭地址或工作地址中包含北京的用户
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"multi_match": {
"query": "北京",
"type": "most_fields",
"fields": [
"家庭住址",
"工作地址"
]
}
}
}'
#查询性别为男的用户
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"term": {
"性别": "男"
}
}
}
}
}'
#查询注册时间为两年内的用户
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"range": {
"注册时间": {"gt" : "now-2y"}
}
}
}
}
}'
排序
#查询所有用户,按注册时间进行排序
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"match_all": {}
},
"sort": {
"注册时间": {
"order": "desc"
}
}
}'
分页
#查询前三条记录
curl -XPOST http://127.0.0.1:9200/myindex/user/_search -d'
{
"query": {
"match_all": {}
},
"from": 0,
"size": 3
}'
带缓存的分页
#进行分页
curl -XPOST http://127.0.0.1:9200/myindex/user/_search?search_type=scan&scroll=5m -d'
{
"query": { "match_all": {}},
"size": 10
}'
#返回_scroll_id
{"_scroll_id":"c2Nhbjs1OzE1MzE6NVR2MmE1WWFRRHFtelVGYlRwNGlhdzsxNTMzOjVUdjJhNVlhUURxbXpVRmJUcDRpYXc7MTUzNDo1VHYyYTVZYVFEcW16VUZiVHA0aWF3OzE1MzU6NVR2MmE1WWFRRHFtelVGYlRwNGlhdzsxNTMyOjVUdjJhNVlhUURxbXpVRmJUcDRpYXc7MTt0b3RhbF9oaXRzOjc7","took":2,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":7,"max_score":0.0,"hits":[]}}
#发送_scroll_id开始查询
curl -XPOST http://127.0.0.1:9200/_search/scroll?scroll=5m
c2Nhbjs1OzE1MzE6NVR2MmE1WWFRRHFtelVGYlRwNGlhdzsxNTMzOjVUdjJhNVlhUURxbXpVRmJUcDRpYXc7MTUzNDo1VHYyYTVZYVFEcW16VUZiVHA0aWF3OzE1MzU6NVR2MmE1WWFRRHFtelVGYlRwNGlhdzsxNTMyOjVUdjJhNVlhUURxbXpVRmJUcDRpYXc7MTt0b3RhbF9oaXRzOjc7