gpt4 book ai didi

mysql - Ruby - Rails - SQL 查询 - 重新排序搜索词中的单词

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:40 25 4
gpt4 key购买 nike

我正在开发一个具有如下设置的搜索功能的项目:

if params[:search_term].present? && params[:search_term].length > 1
@candidates = @candidates.where("title like ?","%#{params[:search_term]}%")
end

客户要求我“放宽”搜索 - 特别是词序。目前,如果有一个标题为 White bar stool 的候选人搜索 White stool bar,它不会返回任何结果。

有什么方法可以让我执行忽略词序的查询吗?还是用不同的词序制作新的搜索词参数、进行多次搜索并合并结果对我来说会更好?

最佳答案

您可以考虑使用 Arel为了这。 Arel 是 rails/activerecord 的底层查询组装器(因此没有新的依赖项),在构建复杂查询时非常有用,因为它提供的深度远比高级 ActiveRecord::QueryMethods

Arel 提供了大量的谓词匹配器选择,包括您的情况 matches_anymatches_all。这些方法采用 StringArray,并使用 Like 将它们拆分为单独的搜索条件。

例如,要搜索包含任何搜索词的所有候选词,您可以使用:

class Candidate < ActiveRecord::Base
def self.search_for(term)
candidates = Candidate.arel_table
where(
candidates[:title].lower.matches_any(
term.split.map { |t| "%#{t.downcase}%" }
)
)
end
end

search_for 的最终结果(给定搜索词“White stool bar”)是:

SELECT [candidates].*
FROM [candidates]
WHERE (
LOWER([candidates].[title]) LIKE '%white%'
OR LOWER([candidates].[title]) LIKE '%stool%'
OR LOWER([candidates].[title]) LIKE '%bar%')

这似乎是您要查找的内容。如果它必须匹配所有术语,您可以改用 matches_all,这将导致:

SELECT [candidates].*
FROM [candidates]
WHERE (
LOWER([candidates].[title]) LIKE '%white%'
AND LOWER([candidates].[title]) LIKE '%stool%'
AND LOWER([candidates].[title]) LIKE '%bar%')

See Here对于所有可用的 Arel 谓词。

这增加了基本转义的好处,以避免 SQL 注入(inject)之类的事情。

关于mysql - Ruby - Rails - SQL 查询 - 重新排序搜索词中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com