我正在使用sunspot/solr进行搜索。我最近发现一些记录没有被索引,因为一个列有时有nil值。
我如何告诉solr索引这些记录?
我的可搜索块是这样的:
searchable do
text :name
text :description
# this price_as_double can sometimes be nil
double :price_as_decimal
text :colors do
colors.map(&:name)
end
text :store do
unless store.nil?
store.name
end
end
string :store do
unless store.nil?
store.name
end
end
text :items_style do
unless items_style.nil?
items_style.name
end
end
time :created_at
boolean :editors_pick
string :sold_out
double :likes
end
对于rails,您需要在迁移
中添加以下函数def change
add_column :product, :price, :string
add_index :product, :price
end
您的迁移将工作,并将允许多个空值(对于大多数数据库引擎)。
但是您对产品类的验证应该如下所示:
验证:price, allow_nil: true
当某些属性是nil
时,您的unless
语句阻止对象被索引。更好的方法是这样写:
searchable do
text :name
text :description
# this price_as_double can sometimes be nil
double :price_as_decimal
text :colors do
colors.map(&:name)
end
text :store do
store.present? ? store.name : ''
end
string :store do
store.present? ? store.name : ''
end
text :items_style do
items_style.present? ? items_style.name : ''
end
time :created_at
boolean :editors_pick
string :sold_out
double :likes
end
如果值为nil
(或空白),则索引为空字符串。