搜索API
from/size
可以使用from和size参数对结果进行分页。from参数定义要获取的第一个结果的偏移量。size参数允许您配置要返回的hits最大数量。
虽然可以将from和size设置为请求参数,但也可以在搜索主体中设置它们。from默认值为0,size大小默认值为10:
GET /_search
{
"from" : 0,
"size" : 10,
"query" : {
"term" : { "user" : "kimchy" }
}
}
注意from + size不能大于index.max_result_window 索引设置,默认为10000。查看Scroll或Search After的API更有效的方式来做深滚动。
排序
允许您在特定字段上添加一个或多个排序。每一种排序都可以反过来。排序是在每个字段级别上定义的,使用特殊的字段名_score按分数排序,_doc按索引顺序排序。
假设索引映射如下:
PUT /my_index
{
"mappings": {
"_doc": {
"properties": {
"post_date": { "type": "date" },
"user": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"age": { "type": "integer" }
}
}
}
}
GET /my_index/_search
{
"sort" : [
{
"post_date" : {
"order" : "asc"
}
},
"user",
{ "name" : "desc" },
{ "age" : "desc" },
"_score"
],
"query" : {
"term" : { "user" : "kimchy" }
}
}
_doc除了是最有效的排序顺序外,没有实际的用例。因此,如果您不关心返回文档的顺序,那么应该按_doc排序。这在滚动时尤其有用。
排序值
返回的每个文档的排序值也作为响应的一部分返回。
排序次序
order选项可以有以下值:
- asc :升序
- desc: 降序
在_score上排序时,顺序默认为desc,在其他任何地方排序时,顺序默认为asc。
排序模式选项
Elasticsearch支持数组或多值字段排序。mode选项控制选择哪个数组值来对其所属的文档进行排序。模式选项可以有以下值:
| 模式 | 作用 |
|---|---|
| min | 选择最小的值。 |
| max | 选择最高的值。 |
| sum | 使用所有值的和作为排序值,仅适用于基于数字的数组字段 |
| avg | 使用所有值的平均数作为排序值,仅适用于基于数字的数组字段 |
| median | 使用所有值的中位数作为排序值,仅适用于基于数字的数组字段 |
在下面的示例中,字段price对每个文档有多个价格。在这种情况下,将根据基于每个文档的平均价格的价格升序对结果命中进行排序:
PUT /my_index/_doc/1?refresh
{
"product": "chocolate",
"price": [20, 4]
}
POST /_search
{
"query" : {
"term" : { "product" : "chocolate" }
},
"sort" : [
{"price" : {"order" : "asc", "mode" : "avg"}}
]
}

浙公网安备 33010602011771号