gpt4 book ai didi

ruby-on-rails - Rails 使用逻辑运算符搜索 ActiveRecord

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:56 25 4
gpt4 key购买 nike

我想知道在 Rails 中解析文本查询的最佳方法是什么,以允许用户包含逻辑运算符?

我希望用户能够输入其中任何一个,或一些等效的:

# searching partial text in emails, just for example
# query A
"jon AND gmail" #=> ["jonsmith@gmail.com"]

# query B
"jon OR gmail" #=> ["jonsmith@gmail.com", "sarahcalaway@gmail.com"]

# query C
"jon AND gmail AND smith" #=> ["jonsmith@gmail.com"]

理想情况下,我们可以使用括号来指示操作顺序,从而变得更加复杂,但这不是必需的。

是否有支持此操作的 gem 或模式?

最佳答案

这是一种可行但效率低下的方法:

user_input = "jon myers AND gmail AND smith OR goldberg OR MOORE"
terms = user_input.split(/(.+?)((?: and | or ))/i).reject(&:empty?)
# => ["jon myers", " AND ", "gmail", " AND ", "smith", " OR ", "goldberg", " OR ", "MOORE"]

pairs = terms.each_slice(2).map { |text, op| ["column LIKE ? #{op} ", "%#{text}%"] }
# => [["column LIKE ? AND ", "%jon myers%"], ["column LIKE ? AND ", "%gmail%"], ["column LIKE ? OR ", "%smith%"], ["column LIKE ? OR ", "%goldberg%"], ["column LIKE ? ", "%MOORE%"]]

query = pairs.reduce([""]) { |acc, terms| acc[0] += terms[0]; acc << terms[1] }
# => ["column LIKE ? AND column LIKE ? AND column LIKE ? OR column LIKE ? OR column LIKE ? ", "%jon myers%", "%gmail%", "%smith%", "%goldberg%", "%MOORE%"]

Model.where(query[0], *query[1..-1]).to_sql
# => SELECT "courses".* FROM "courses" WHERE (column LIKE '%jon myers%' AND column LIKE '%gmail%' AND column LIKE '%smith%' OR column LIKE '%goldberg%' OR column LIKE '%MOORE%' )

但是,正如我所说,像这样的搜索效率极低。我建议您使用全文搜索引擎,例如 Elasticsearch .

关于ruby-on-rails - Rails 使用逻辑运算符搜索 ActiveRecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31392376/

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