-->

获取一列的最大值和最小值与思考狮身人面像(Get max and min value of a co

2019-10-28 11:15发布

我使用Rails的工作和思维狮身人面像。 我有索引如下一个型号产品(只显示相关信息)

define_index do
   indexes :name, :as => :name, :sortable => true
   indexes color, :facet => true
   ...
   indexes price, :as => :range, :facet => true
   has created_at, price, root_category_id
   ...
end

我需要的是与当前搜索的最大价格拿到产品。 我已经试过类似

 Product.search('', :select => 'MAX(price)')

但它返回我一个烂摊子。

>> Product.search_for_ids( :select => 'MAX(price)')
Sphinx Query (3.0ms)  
Sphinx  Found 732 results
Product Load (0.4ms)  SELECT MAX(price) FROM `products` WHERE `products`.`id` IN (388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 401, 402, 403, 404, 405, 406, 407, 408)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

我真不明白它为什么这样做奇怪的查询,为什么它补充说,在哪里以及为什么它返回一个数组。

问候,佛朗哥。

Answer 1:

答案很简单:狮身人面像不能返回汇总数据 - 它总是返回文档记录(在这种情况下,产品)。 你将不得不使用ActiveRecord / SQL对于这种类型的查询。

至于为什么你试图返回奇数值:与思考狮身人面像v2和更早的:select选项,通过对底层的ActiveRecord调用传递时,狮身人面像结果被翻译成ActiveRecord的选项(SQL调用就可以看到)。 您移除SELECT子句中的主键,所以思考狮身人面像不能匹配狮身人面像结果产品实例,因此无返回每个失败的匹配。



文章来源: Get max and min value of a column with thinking sphinx