您的位置:首页 > 其它

6.3.3 Sort (for Elasticsearch v2.2)

2016-03-04 13:59 162 查看

Sort 原文链接  翻译:AbnerGong

允许在指定的字段(fields)上添加一个或多个排序。每个排序也可以是反向的(reversed)。排序定义在每个字段水平(field level)上,用打分排序用特定的域名_score,用索引序号排序用_doc。

{
"sort" : [
{ "post_date" : {"order" : "asc"}},
"user",
{ "name" : "desc" },
{ "age" : "desc" },
"_score"
],
"query" : {
"term" : { "user" : "kimchy" }
}
}


【注意】_doc除了是最有效率的排序方式外没有真正的使用情况(has no real use-case)所以如果你不关心文档返回的顺序,你应该用_doc排序。这在使用scrolling时尤其有帮助。

排序值(Sort Values)

每个文档的排序值也会作为返回结果的一部分返回。

排序方式(Sort Order)

order
选项可以有如下值:

asc
:升序排列

desc
:降序排列

在使用
_score
时默认使用降序,使用其它排序时默认为
asc
升序。

排序模式选项(Sort mode option)

Elasticsearch支持用数组或多值字段排序。
mode
选项控制在排序文档时选取数组中的哪个值。
mode
选项能有如下值:

min:选取最小值

max:选取最大值

sum:使用数值的和作为排序值。只能用于基于数字的数组字段

avg:使用数值的均值作为排序值。同上

median:使用数值的中位数作为排序值。同上

排序模式使用样例:

在如下样例中,价格字段在每个文档中都有多个价格。在这个情况中选出的结果(result hits)将会基于每个文档中的平均价格升序排序。

curl -XPOST 'localhost:9200/_search' -d '{
"query" : {
...
},
"sort" : [
{"price" : {"order" : "asc", "mode" : "avg"}}
]
}'


在嵌套对象内排序

Elasticsearch也支持用一个或多个嵌套的对象内的字段排序。在已经存在的排序选项的顶端可以支持如下嵌套字段排序。

nested_path


…………

nested_filter


……

curl -XPOST 'localhost:9200/_search' -d '{
"query" : {
...
},
"sort" : [
{
"offer.price" : {
"mode" :  "avg",
"order" : "asc",
"nested_path" : "offer",
"nested_filter" : {
"term" : { "offer.color" : "blue" }
}
}
}
]
}'


嵌套排序也支持(is supported when sorting by)脚本或地理距离排序。

缺失值(Missing Values)

missing
变量指定了(specifies)缺失某个字段的文档应该如何处理(treated):
missing
值会被设为
_last
,
_first
,或者自定义值(将会当做缺失值的文档的排序值)。例如:

{
"sort" : [
{ "price" : {"missing" : "_last"} },
],
"query" : {
"term" : { "user" : "kimchy" }
}
}


【注意】如果嵌套的内部对象不匹配
nested_filter
那么就会用缺失值

忽略未映射的字段(Ignoring Unmapped Fields)

地理距离排序

允许使用
_geo_distance
排序。样例:

{
"sort" : [
{
"_geo_distance" : {
"pin.location" : [-70, 40],
"order" : "asc",
"unit" : "km",
"mode" : "min",
"distance_type" : "sloppy_arc"
}
}
],
"query" : {
"term" : { "user" : "kimchy" }
}
}


distance_type
:如何计算距离。 ……

…………

(省略大量内容)

…………

多参考的得分

多地理点能以包含任何
geo_point
格式的数组传递,例如:

"pin.location" : [[-70, 40], [-71, 42]]
"pin.location" : [{"lat": 40, "lon": -70}, {"lat": 42, "lon": -71}]


等等(and so forth)

一个文档的最终距离将是在文档中的所有点到排序请求中给定的所有点的
min/max/avg
(通过
mode
定义)距离。

基于排序的脚本

允许基于自定义脚本的排序,这里是一个样例:

{
"query" : {
....
},
"sort" : {
"_script" : {
"type" : "number",
"script" : {
"inline": "doc['field_name'].value * factor",
"params" : {
"factor" : 1.1
}
},
"order" : "asc"
}
}
}


追踪得分(Track Score)

默认在一个字段上排序时,是不计算得分的。通过设定track_scores为true,得分将会仍然被计算和追踪(tracked)

{
"track_scores": true,
"sort" : [
{ "post_date" : {"reverse" : true} },
{ "name" : "desc" },
{ "age" : "desc" }
],
"query" : {
"term" : { "user" : "kimchy" }
}
}


内存考虑(Memory Considerations)

排序时(when sorting),相关的排序字段值被加载到内存中。这意味着每个碎片,应该有足够的内存来容纳它们(contain them)。对于基于类型的字符串,字段排序上不应该分词/标记化。对于数字类型,如果可能的话,建议明确设置类型为更窄的类型(如short,integer和float)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: