【问题标题】:django haystack backed by elasticsearch seems to order Decimal as string由 elasticsearch 支持的 django haystack 似乎将 Decimal 排序为字符串
【发布时间】:2015-09-02 23:06:16
【问题描述】:

我有这个模型(django-oscar 产品):

class Product(AbstractProduct):
    # ...
    price_display = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
    # ...

由 haystack 索引:

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    # ...
    price = indexes.DecimalField(null=True)
    # ...
    def prepare_price(self, obj):
        return obj.price_display or Decimal('0.0')

Haystack 由 elasticsearch 支持

pip freeze | grep elastic
elasticsearch==1.6.0
pyelasticsearch==1.4
pip freeze | grep hays
django-haystack==2.1.0

现在这个查询集:

# ...
qs = qs.filter(text__contains=q)
qs = qs.order_by('price')

返回以这种方式排序的(正确找到的)对象:

120  130  24  300 ... 9

不知道哪里错了……

【问题讨论】:

    标签: elasticsearch django-haystack


    【解决方案1】:

    Haystack(至少在我使用的版本中)将 Decimal 字段发送到 elastic : "price":{"type":"string","store":true,"term_vector":"with_positions_offsets","analyzer":"snowball"},

    所以它“似乎”不像字符串那样排序,它是在排序一个字符串......

    我已将代码更改为使用浮点数,不是这样的问题,我们现在不再谈论金钱了。

    price = indexes.FloatField(null=True)
    
    def prepare_price(self, obj):
        if obj.price_display:
            return float(str(obj.price_display))
        return float('0.0')
    

    现在它将字段发送为: "price":{"type":"float","index":"analyzed","store":true},

    和订购工作,耶

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2011-03-26
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多