首页 > 解决方案 > 如何根据来自客户端的搜索查询查询数据,然后根据组的优先级对查询结果进行排序

问题描述

在 rails / postgres 应用程序内部,有一个搜索字段(客户端),可让用户搜索网站项目(通过 WebsiteItem 模型)。搜索被 rails / postgres 后端拦截,当用户单击“提交搜索”时,rails 控制器最终将导致执行看起来像这样的查询:

def search_for_items(items)
          results = ::WebsiteItem
            .joins(:meta_item)
            .joins(
              <<-SQL
                LEFT JOIN accounts ON meta_item.id = accounts.meta_item_id
                LEFT JOIN users ON users.id = accounts.user_id
              SQL
            )
            .where(
              (
                <<-SQL
                 (
                    COALESCE(website_items.title, '') ||
                    COALESCE(website_items.description, '') ||
                    COALESCE(accounts.data, '') ||
                     ... more conditions, 
                  ) LIKE '%' || :search_query || '%'
                SQL
              ),
            )
        end

当前,当用户搜索“hello”时,将选择标题为“hello”的项目以及具有“hello”的帐户数据,以及附加的过滤器参数。这很好,确实找到了需要找到的项目,

问题-> 此数据未排序。 要求: -> 标题为“hello”的网站项目应出现在结果中的“数据”列中包含“hello”的帐户之前(因为网站项目对客户而言可能比帐户数据更重要)

有没有办法不按特定列而是按数据组对搜索查询结果进行排序?例如,一组用于项目标题和描述,另一组用于帐户,并确保一组结果将在另一组结果之前排序?这可以在 postgres db 层或 rails 层实现

楷模:

WebsiteItem, MetaItem, Account, User (tables: website_items, meta_items, accounts, users)

User (id, firstname, lastname)
WebsiteItem (id, title, description, meta_item_id)
Account (id, data, meta_item_id, user_id) 

查询的预期结果:“hello”: 4 个项目:2 个帐户在其数据中包含“hello”(item1,item3)2 个标题为“hello”(item2,item4)的项目当前按顺序给出:(item1 ,item2,item3,item4)但要求​​应该是查询结果将按以下顺序排列:(item2,item4,item1,item3)因为items.title在搜索(客户端)中的优先级高于accounts.data

标签: ruby-on-railspostgresql

解决方案


推荐阅读