上一篇文章介绍了基于 url 的搜索,这次要讲一种更高级的搜索方法——请求体搜索(Request Body Search),搜索参数不是写在 url 上,而是作为请求的数据发送。利用 Query DSL 的语法可以组合出更加灵活的搜索。
简单的例子
GET /customer/_search
{
"query" : {
"term" : { "user" : "kimchy" }
}
}
对应的curl 格式是:
curl -X GET "localhost:9200/customer/_search" -H 'Content-Type: application/json' -d'
{
"query" : {
"term" : { "user" : "kimchy" }
}
}
'
查询返回的结果
{
"took": 1,
"timed_out": false,
"_shards":{
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits":{
"total" : 1,
"max_score": 1.3862944,
"hits" : [
{
"_index" : "twitter",
"_type" : "_doc",
"_id" : "0",
"_score": 1.3862944,
"_source" : {
"user" : "kimchy",
"message": "trying out Elasticsearch",
"date" : "2009-11-15T14:12:12",
"likes" : 0
}
}
]
}
}
当过本次查询的统计,和查询到的文档。
from 和 size
与关系数据库类似,ES也可以指定from 和 size,举上面的例子
GET /customer/_search
{
"query" : {
"term" : { "user" : "kimchy" }
},
from: 0,
size: 20
}
from 从0开始,size 最大不能大于 index.max_result_window 的配置,默认是10000。
排序 sort
可以指定某个或者多个字段作为排序字段。有两个特殊的排序字段,_score 和 _doc,_score 是文档匹配的 score,_doc 是文档索引时候的顺序。
在能够使用sort之前,必须为排序的字段指定类型(须在建立索引之前完成),例如
PUT /my_index
{
"mappings": {
"_doc": {
"properties": {
"post_date": { "type": "date" },
"user": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"age": { "type": "integer" }
}
}
}
}
然后就可以指定字段排序了,两种顺序 asc 和 desc
GET /my_index/_search
{
"sort" : [
{ "post_date" : {"order" : "asc"}},
"user",
{ "name" : "desc" },
{ "age" : "desc" },
"_score"
],
"query" : {
"term" : { "user" : "kimchy" }
}
}
sort mode
当排序的字段是数组的时候,该如何告诉 ES 排序呢?sort 还可以指定 mode 属性,min,max,sum,avg,或者 median,含义如字面理解的一样。
举例
PUT /my_index/_doc/1?refresh
{
"product": "chocolate",
"price": [20, 4]
}
GET /my_index/_search
{
"query" : {
"term" : { "product" : "chocolate" }
},
"sort" : [
{"price" : {"order" : "asc", "mode" : "avg"}}
]
}
sort nexted
当排序的字段是个对象里的属性该怎么办?例如 offer.price,
POST /_search
{
"query" : {
"term" : { "product" : "chocolate" }
},
"sort" : [
{
"offer.price" : {
"mode" : "avg",
"order" : "asc",
"nested": {
"path": "offer",
"filter": {
"term" : { "offer.color" : "blue" }
}
}
}
}
]
}
offer.price 是自定义的排序名称,必要的关键字时 nested 和 path,path 表示排序的属性是哪个对象的属性;filter 可选,一帮跟 query 的查询条件一样。