V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
shiziwen
V2EX  ›  Django

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

  •  
  •   shiziwen · 2015-08-07 11:23:08 +08:00 · 2827 次点击
    这是一个创建于 3187 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在使用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

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

    3 条回复    2015-11-14 02:25:18 +08:00
    Carrycat
        1
    Carrycat  
       2015-11-12 17:00:51 +08:00 via iPhone
    我的 app 搜索功能也使用了 haystack ,目前 haystack 还是有很多缺点比如无法 cursor pagination- cursor 分页功能这个要求就是 unique order 所以任何 orderby 都应该再加 id : order_by('distance','pk')
    于是我自己改了 haystack backends 让他不仅支持以上功能还支持 cursor pagination.
    对了我是 Solr 感兴趣的话我可以 update github
    shiziwen
        2
    shiziwen  
    OP
       2015-11-13 19:09:10 +08:00
    @Carrycat
    多谢,
    请问你 git 地址多少?
    Carrycat
        3
    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:
    这个判断删除掉就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3304 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:35 · PVG 19:35 · LAX 04:35 · JFK 07:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.