多关键词数据库搜索
我目前正在模型中使用范围来在数据库中执行搜索。我可以堆叠这些范围,它将输出与所有参数匹配的结果。
scope :search_between, lambda{|begin_date, end_date|
where "sub.date BETWEEN ? AND ?", begin_date, end_date
}
我遇到的问题是集成关键字搜索,它将搜索整个数据库并输出包含关键字总和的结果。我想做这样的事情(为简单起见而显示):
scope :keywords, lambda{|search|
search.chomp.split(/,\s*/) do |item|
where "date like ? or city like ? or state like ?", "%#{item}%" and
where "date like ? or city like ? or state like ?", "%#{item}%" and
where "date like ? or city like ? or state like ?", "%#{item}%"
end
}
我目前正在使用这样的东西来负责搜索多个列:
scope :keywords, lambda{|search|
search.chomp.split(/,\s*/) do |item|
where(Sub.column_names.map {|cn| "#{cn} like ?" }.join("or "), "%#{item}%"] Sub.column_names.size)).join(' AND ')
end
}
我的问题是我想在范围内执行多个“where()”。可能吗?如果可能的话,如何实现?
I am currently using scopes in my model to perform searches within a database. I can stack these scopes and it will output results matching all parameters.
scope :search_between, lambda{|begin_date, end_date|
where "sub.date BETWEEN ? AND ?", begin_date, end_date
}
What I am having trouble with is integrating a keywords search that will search the entire database and output the results that contain the sum of the keywords. I would like to do something like this (displayed for simplicity):
scope :keywords, lambda{|search|
search.chomp.split(/,\s*/) do |item|
where "date like ? or city like ? or state like ?", "%#{item}%" and
where "date like ? or city like ? or state like ?", "%#{item}%" and
where "date like ? or city like ? or state like ?", "%#{item}%"
end
}
I am currently using something like this to take care of searching multiple columns:
scope :keywords, lambda{|search|
search.chomp.split(/,\s*/) do |item|
where(Sub.column_names.map {|cn| "#{cn} like ?" }.join("or "), "%#{item}%"] Sub.column_names.size)).join(' AND ')
end
}
My problem is that I want to do multiple "where()'s" in the scope. Is it possible and if so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将其变成返回范围的方法即可:
The drawback is that you can't chain keywords off of other scopes, but you can chain other scopes off of keywords.
Just turn it into a method that returns a scope:
The drawback is that you can't chain keywords off of other scopes, but you can chain other scopes off of keywords.
我认为使用数据库进行全文搜索将达到极限。
您是否考虑过使用 Solr 或 Sphinx 用于全文搜索?如果您想使用第三方服务,还有 IndexTank。
对于 solr,有 rubygems 可以帮助您:sunspot、solrsan(我是作者)
Sunspot 绝对是功能更全面的,而 solrsan 是一个准系统层。
I think you will be hitting the limit with using the database for full text search.
Have you looked into using Solr or Sphinx for your full text searches? There's also IndexTank if you want to use a 3rd party service.
For solr, there are rubygems available to help you: sunspot, solrsan(i'm the author)
Sunspot is definitely more full-featured and solrsan is a barebones layer.