我有以下查询来搜索我的客户数据库并成功执行:
SELECT "customers".* FROM "customers" WHERE ((("customers"."first_name" IN ('John', 'Doe') OR "customers"."last_name" IN ('John', 'Doe')) OR "customers"."email" IN ('John', 'Doe')) OR "customers"."main_phone" IN ('John', 'Doe'))
等效的 Rails 查询是:
array = ["John","Doe","111-111-1111"]
Customer.where(first_name: array).or(customers.where(last_name: array)).or(customers.where(email: array)).or(customers.where(main_phone: array))
这很好用,但是我想对结果进行排名。例如,如果记录 # 1 匹配名字和姓氏,我希望该记录显示在结果的顶部。我怎么能这样做?
最佳答案
where 和 or actually 的组合创建一个没有“优先级”结果的 SQL 查询 你不得不 1.将其分解为单独的查询 2.对于找到的每条记录,计算找到的查询次数 3. 按此计数器降序排列您的结果
这是一些代码(它可以更漂亮):
class Customer < ApplicationRecord
def self.relevance_search(query)
matches = []
matches << Customer.where(first_name: query)
matches << Customer.where(last_name: query)
matches << Customer.where(email: query)
matches << Customer.where(main_phone: query)
counter = {}
matches.each do |match|
match.each do |match_result|
id = match_result.id
if counter.key? id
counter[id] += 1
else
counter[id] = 1
end
end
end
counter.map { |id, occurrences| { relevance: 100*(occurrences/4.0), customer: Customer.find(id) } }.sort_by { |r| r[:relevance] }.reverse!
end
end
用法:
Customer.relevance_search ["John", "Doe", "111-111-1111"]
返回值是按相关度排序的数组 %
享受 :)
关于sql - 排名查询结果 - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010712/