ruby-on-rails - 如何根据来自客户端的搜索查询查询数据,然后根据组的优先级对查询结果进行排序
问题描述
在 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
解决方案
推荐阅读
- regex - 仅用打印的十六进制格式替换文本文件中的某些字符
- reactjs - 材质ui下一个文本字段下划线颜色
- entity-framework - Z.EntityFramework.Plus MemberInitExpression 错误
- java - Long Literals in Java
- docker - Docker 中的 Solr,如何在挂载的卷目录中创建共享的分布式集合
- android - 查询 firebase 数据库并检索特定数据
- c# - 为什么服务器可能不会收到附加到使用 HttpClient 的请求的证书?
- javascript - 如何更改有关 if else 语句的角度 fxLayout(行到列)
- unit-testing - 如何为多部分/表单数据上传 cdc 测试创建 PACT
- python - 根据集合上的元素重复数据框