Ruby on rails 如何将部分字符串与数据库';s对象';s属性?Regexp?
我有一个包含电影列表的数据库。典型条目如下所示:Ruby on rails 如何将部分字符串与数据库';s对象';s属性?Regexp?,ruby-on-rails,regex,database,postgresql,Ruby On Rails,Regex,Database,Postgresql,我有一个包含电影列表的数据库。典型条目如下所示: id: 1, title: "Manhatten and the Murderer", year: 1928, synopsis: 'some text...' rating: 67, genre_id, etc. etc. Movie.where('title LIKE ?','Batman%') 现在,我正在尝试通过一系列的搜索测试,到目前为止,我已经通过了一个测试用例,如果你在文本字段中键入标题“Manhatten and t
id: 1,
title: "Manhatten and the Murderer",
year: 1928,
synopsis: 'some text...'
rating: 67,
genre_id, etc. etc.
Movie.where('title LIKE ?','Batman%')
现在,我正在尝试通过一系列的搜索测试,到目前为止,我已经通过了一个测试用例,如果你在文本字段中键入标题“Manhatten and the杀人犯”,它将找到你想要的电影。问题在于部分匹配
现在我想要一种搜索“Manhatt”并匹配“Manhatten和凶手”记录的方法。我也希望它能与任何一部有“曼哈特”的电影相匹配。例如,它可能会返回2或3个其他名称,如标题:“我在曼哈顿的生活”,标题:“曼哈顿的大苹果”等
以下是迄今为止我在电影模型中使用的代码:
def self.search(query)
# Replace this with the appropriate ActiveRecord calls...
if query =~ where(title:)
#where(title: query)
binding.pry
end
end
我的问题是,我如何设置这个?我的问题是“where(title:)行。一个想法是使用Regexp来匹配title属性。任何帮助都将不胜感激!谢谢。您不需要regex来查找具有搜索字符串的电影。您可以像这样使用SQL查询:
id: 1,
title: "Manhatten and the Murderer",
year: 1928,
synopsis: 'some text...'
rating: 67,
genre_id, etc. etc.
Movie.where('title LIKE ?','Batman%')
这将返回所有以“蝙蝠侠”开头的电影
这将返回所有标题中包含蝙蝠侠的电影。
我想您已经发现“%”在查询中是一个小丑字符。使用一个查询来搜索中间的子字符串:
name = "Manhattan"
Movie.where("title like ?", "%#{name}%")
例如:
将带给你:%Manhattan
爱在曼哈顿
将获得:Manhattan%
曼哈顿和公司
会让你们俩都满意:%Manhattan%
[爱在曼哈顿、曼哈顿和公司]
id: 1,
title: "Manhatten and the Murderer",
year: 1928,
synopsis: 'some text...'
rating: 67,
genre_id, etc. etc.
Movie.where('title LIKE ?','Batman%')
添加app/index/movie\u index.rb
:
ThinkingSphinx::Index.define :movie, :with => :active_record do
# fields
indexes title, :sortable => true
indexes synopsis
end
使用rake ts:Index为数据编制索引
然后使用运行Sphynx:rake ts:start
您可以像这样搜索:
id: 1,
title: "Manhatten and the Murderer",
year: 1928,
synopsis: 'some text...'
rating: 67,
genre_id, etc. etc.
Movie.where('title LIKE ?','Batman%')
Movie.search:conditions=>{:synosis=>“曼哈顿”}
Elastic Search是ThinkingSphinx的一个很好的替代方案,它甚至有很多优点,所以你一定要看看什么最适合你……希望这有帮助!一个选择是在你的Rails应用程序旁边运行搜索服务器。这当然是我的解决方案。这条路线提供了Rails中找不到的大量功能这本身可能有些过分,但值得考虑
我使用Sphinx,并使用思考Sphinx gem实现它
资源:
如果你想不区分大小写,在PostgreSQL中你可以使用ilike
。或者使用~*
操作符和regexp。我知道你在那里做了什么。