【ELK】Elasticsearch入门05 --基础语法 综合条件查询 排序 分页
综合条件查询
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
## 条件:must,表示[]中条件都需要符合
## 条件:should,表示[]中条件只需要符合一个即可查出
## 条件:must_not,表示[]中条件一个都不符合即可查出
"must" :
[
{
"match" :
{"name" : "zhang san"}
},
{
## 范围查询
"range" :
{
"age":{
"from" : "22",
"to" : "33"
}
}
}
]
}
}
}
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
"must" :
[
{
"match" :
{"name" : "zhang san"}
},
{
"range" :
{
"age":{
"from" : "22",
"to" : "33"
}
}
}
]
}
}
}
返回:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.9983525,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.9983525,
"_source" : {
"name" : "zhang san",
"age" : "22"
}
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "5",
"_score" : 1.8416345,
"_source" : {
"name" : "zhang san li",
"age" : "22"
}
}
]
}
}
注意:
在条件查询中,在must中的条件会影响检索结果的最终得分_source,所以像未进行分词的字段,如数值类型,keyword不建议放在bool的{}中作为条件。推荐使用filter进行过滤
过滤查询
过滤查询不会影响字段的_source得分
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
"must" :
[
{
"match" :
{"name" : "zhang san"}
}
],
"filter":{
"range" : {
"字段名": {
"from":"开始值",
"to":"结束值"
}
}
}
}
},
"from": 当前页码,
"size": 每页长度
}
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
"must" :
[
{
"match" :
{"name" : "zhang san"}
}
],
##过滤 按照age栏位值的范围22-33
"filter":{
"range" : {
"age": {
"from":"22",
"to":"33"
}
}
}
}
},
## 分页第0页,每页长度为1
"from": 0,
"size": 1
}
返回:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 0.9983525,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.9983525,
"_source" : {
"name" : "zhang san",
"age" : "22"
}
}
]
}
}
按照字段进行排序
如果进行排序那么返回的_source得分会变为null
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
"must" :
[
{
"match" :
{"name" : "zhang san"}
}
],
"filter":{
"range" : {
"age": {
"from":"22",
"to":"33"
}
}
}
}
},
##排序 排序方式分为desc 和ase
"sort": [
{
"字段名": {
"order":"排序方式"
}
}
],
"from": 0,
"size": 1
}
GET /test/_search
{
"_source": {"excludes":"sex"},
"query" : {
"bool": {
"must" :
[
{
"match" :
{"name" : "zhang san"}
}
],
"filter":{
"range" : {
"age": {
"from":"22",
"to":"33"
}
}
}
}
},
"sort": [
{
"age": {
"order":"desc"
}
}
],
"from": 0,
"size": 1
}
返回:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "zhang san",
"age" : "22"
},
"sort" : [
22
]
}
]
}
}