我正在尝试编写一个相对简单的算法来搜索多个属性的字符串
给定一些数据:
一些数据:
1: name: 'Josh', location: 'los angeles'
2: name: 'Josh', location: 'york'
搜索字符串:“josh york”
结果应该是 [2, 1] 因为该查询字符串命中第二条记录两次,而第一条记录一次。
在这里假设不区分大小写是安全的。
所以这是我到目前为止在红宝石/活动记录中所拥有的:
query_string = "josh new york"
some_attributes = [:name, :location]
results = {}
query_string.downcase.split.each do |query_part|
some_attributes.each do |attribute|
find(:all, :conditions => ["#{attribute} like ?", "%#{query_part}%"]).each do |result|
if results[result]
results[result] += 1
else
results[result] = 1
end
end
end
end
results.sort{|a,b| b[1]<=>a[1]}
我对这种方法的问题是它会产生大量查询(query_string.split.length * some_attributes.length)。
我可以通过减少查询数量以某种方式提高效率吗?
我可以在 ruby 中进行排序,尽管如果可以以某种方式将其卡在 SQL 中,那也很好。