django haystack 中使用 Spatial Search order_by 的一个问题

2015-08-07 11:23:08 +08:00
 shiziwen

最近在使用haystack,具体就是计算周边一定范围内的场馆,并按照距离排序。
使用如下代码可以实现:

sqs = SearchQuerySet().dwithin('location', ninth_and_mass, D(mi=2)).distance('location', ninth_and_mass).order_by('distance')

但是,发现使用order_by的时候有一些限制,如果按照距离排序,必须把distance放在order_by的第一个位置,即order_by('distance', 'other_filed')
如果使用order_by('other_filed', 'distance'),结果会把other_filed的值当做距离值来处理。
例如我有一个字段count,当使用order_by('count', 'distance')的时候,结果计算出来的distance的值就是count的值。
如果反过来,使用order_by('distance', 'count'),结果正常,但是这种排序方式不是我想要的。

我是结合rest framework使用的,serializers使用了drf_haystack提供的HaystackSetializer:
class LocationSerializer(HaystackSerializer):

仔细查看了一个haystack的文档,发现一段说明:
You can not specify both a distance & lexicographic ordering. If you specify more than just distance or -distance, Haystack assumes distance is a field in the index & tries to sort on it.
http://django-haystack.readthedocs.org/en/v2.4.0/spatial.html#ordering

貌似是说不能同时使用distance和其它字段进行排序。

不知道大家有没有遇到类似的问题。

我现在的解决方法,是分两次取我需要的值,即以count进行分割,先把满足count一定条件的出去来,再取另一部分,然后再放到一起。
但没有找到连接两个SearchQuerySet()的方法,我是先转换成list,然后再拼接在一起的,但是这种方法的效率会很低,因为转成list的时候,会把SearchQuerySet()中的值全部取出来。如果结果集很大的话,势必会有性能上的问题。
下面是我的方法:

queryset_top_list = list(queryset_top)
queryset_other_list = list(queryset_other)
queryset_top_list.extend(queryset_other_list)
queryset = queryset_top_list

不知道大家有没有好的方法。
多谢。

2846 次点击
所在节点    Django
3 条回复
Carrycat
2015-11-12 17:00:51 +08:00
我的 app 搜索功能也使用了 haystack ,目前 haystack 还是有很多缺点比如无法 cursor pagination- cursor 分页功能这个要求就是 unique order 所以任何 orderby 都应该再加 id : order_by('distance','pk')
于是我自己改了 haystack backends 让他不仅支持以上功能还支持 cursor pagination.
对了我是 Solr 感兴趣的话我可以 update github
shiziwen
2015-11-13 19:09:10 +08:00
@Carrycat
多谢,
请问你 git 地址多少?
Carrycat
2015-11-14 02:25:18 +08:00
@shiziwen
https://github.com/DrChai/Haystack-SolrEnginePlus 不过一直没有 documentation ,最近没有时间 Update ,毕竟是我们自己用的 Interface not friendly 。
如果你不需要 Cursor Pagin 而且也用 Solr 的话,其实可以很好改动的,在 python34\Lib\site-packages\haystack\backends\solr_backend.py
Line159 if sort_by in ['distance asc', 'distance desc'] and distance_point:
这个判断删除掉就好了

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

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

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

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

© 2021 V2EX