Elasticsearch 如何用 script_fields 计算出来的字段进行排序?

2015-08-31 14:39:09 +08:00
 tumayun

示例如下:

curl -X GET 'http://localhost:9200/users/user/_search?pretty' -d '{
  "script_fields":{
    "distance":{
      "params":{
        "lat":23.1191,
        "lon":113.31
      },
      "script":"doc[\"location\"].distanceInKm (lat, lon )",
      "lang":"groovy"
    }
  }
}
'

返回如下结果:

# 2015-08-31T14:29:46+08:00 [200] (0.005s )
#
# {
#   "took":2,
#   "timed_out":false,
#   "_shards":{
#     "total":5,
#     "successful":5,
#     "failed":0
#   },
#   "hits":{
#     "total":11,
#     "max_score":1.0,
#     "hits":[
#       {
#         "_index":"users",
#         "_type":"user",
#         "_id":"4",
#         "_score":1.0,
#         "fields":{
#           "distance":[
#             12873.486133286819
#           ]
#
# }
#       },
#      ...

请问如何用 fields.distance 进行排序?

在 sort 中,不知道如何取到 distance 的值,所以也就无法写出 sort 子句,求解惑!!

14452 次点击
所在节点    Elasticsearch
4 条回复
tajpure
2015-08-31 17:30:45 +08:00
参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html


我一般用 Client 做查询,没怎么用过 curl. 不过以上应该可以解决 LZ 的问题.
EPr2hh6LADQWqRVH
2015-08-31 19:55:25 +08:00
es 对地理坐标有专门优化,看下文档。
看来不是任何时候 Msql 都是最成熟稳定对吧
sunchen
2015-09-01 03:28:50 +08:00
yn
2016-06-28 09:22:18 +08:00
curl -X GET 'http://localhost:9200/users/user/_search?pretty' -d '{
"sort" : [ {
"_geo_distance" : {
"location" : [ {
"lat" : 23.1191,
"lon" : 113.31
} ],
"unit" : "km",
"distance_type" : "arc"
}
}]
}'

使用这个相当于 利用 script_fields 的 distanceInKm 计算 然后排序

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/217312

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX