sql - 排名查询结果 - Rails

标签 sql ruby-on-rails ruby postgresql ruby-on-rails-5

我有以下查询来搜索我的客户数据库并成功执行:

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/

相关文章:

mysql - 如何使用分组获取(选择)特定列中具有最大值的行

ruby-on-rails - Sidekiq 在每个时区的特定时间执行

ruby-on-rails - 通过比较两个日期范围是否重叠来过滤 Rails 查询

.net - winforms 应用程序中的查询设计器

mysql - 计算与查询匹配的特定行数

mysql - 对 DATE 列建立索引有什么优势吗?

ruby-on-rails - 从 ActiveRecord 对象中提取两个属性的快捷方式?

ruby-on-rails - 如何完全卸载rails,ruby和rubygems?

ruby-on-rails - 将 Ruby 时间戳转换为 Epoch 中的秒数并返回

ruby-on-rails - 使用短信或电子邮件发送设备确认说明