【问题标题】:How can I match a partial string to a database's object's attribute? Regexp?如何将部分字符串与数据库对象的属性匹配?正则表达式?
【发布时间】:2014-05-01 01:39:59
【问题描述】:

我有一个包含电影列表的数据库。一个典型的条目如下所示:

id: 1, 
title: "Manhatten and the Murderer", 
year: 1928, 
synopsis: 'some text...' 
rating: 67, 
genre_id, etc. etc.

现在我正在尝试通过一系列搜索测试,到目前为止,我已经通过了一个测试用例,如果您在文本字段中输入标题“Manhatten and the Murderer”,它会找到您想要的电影想。问题在于部分匹配。

现在我想要一种方法来搜索“Manhat”并匹配记录“Manhatten and the Murderer”。我还希望它与任何包含“Manhat”的电影相匹配。例如,它可能会返回 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:) 行。一个想法是使用正则表达式来匹配标题属性。任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: ruby-on-rails regex database postgresql


    【解决方案1】:

    使用在两者之间搜索子字符串的查询:

    name = "Manhattan"
    Movie.where("title like ?", "%#{name}%")
    

    例如:

    • %Manhattan 会得到你:Love in Manhattan
    • Manhattan% 将得到:Manhattan and Company
    • %Manhattan% 会得到你们两个:[Love in Manhattan, Manhattan and Company]

    但是,如果您要搜索电影简介,则应使用 Thinking SphinxElastic Search

    例如,使用 Elastic Search,您可以这样设置概要:

    添加app/indices/movie_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

    你可以这样搜索:

    Movie.search :conditions => {:synopsis => "Manhattan"}


    Elastic Search 是 ThinkingSphinx 的绝佳替代品,甚至还有一个 RailsCast 关于它,所以你一定要看看什么最适合你...希望这会有所帮助!

    【讨论】:

    • 如果你想不区分大小写,在 PostgreSQL 中你可以使用ilike。或使用~* 运算符和正则表达式。
    【解决方案2】:

    您不需要正则表达式来查找具有搜索字符串的电影。您可以像这样使用 SQL 查询:

    Movie.where('title LIKE ?','Batman%')
    

    这将返回所有以“蝙蝠侠”开头的电影

    Movie.where('title LIKE ?','%Batman%')
    

    这将返回所有标题中包含蝙蝠侠的电影。 我想你在查询中发现 '%' 是一个小丑字符。

    【讨论】:

    • 我知道你在那里做了什么。
    【解决方案3】:

    一种选择是在 Rails 应用程序旁边运行搜索服务器。这当然是我的解决方案。这条路线提供了 Rails 本身所没有的大量功能,可能有点矫枉过正,但值得考虑。

    我使用 Sphinx 并使用 thinking-sphinx gem 实现它。

    资源:

    http://pat.github.io/thinking-sphinx/

    http://sphinxsearch.com/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2015-10-25
      相关资源
      最近更新 更多