Ruby:在倒排索引中搜索部分匹配

标签 ruby full-text-search

我需要在倒排索引中搜索部分匹配,以下代码适用于完全匹配但不适用于部分匹配。从 http://rosettacode.org/wiki/Inverted_Index 的示例中修改了此内容(不再适用于 Ruby1.9.3)

请问如何最有效地做到这一点? 请不要建议使用 Lucene、Sphinx 等,除非你知道一个轻量级、简单和纯 Ruby 解决方案,想自己做。

@data = {"contents"=>["1.txt", "2.txt"], "of"=>["1.txt", "2.txt"], "file"=>["1.txt", "2.txt"], "one"=>["1.txt"], "two"=>["2.txt"]}

def search words
  result = []
  words.each do |word|
    result << @data[word] if @data[word] #should do a partial match
  end
  result
end

p search ['of'] #=> [["1.txt", "2.txt"]]
p search ['one'] #=> [["1.txt"]]
p search ['on']  #=> []                    <<should become [["1.txt"]]

最佳答案

定义搜索如下:

def search words
  words.map do |word|
    matches = @data.keys.select {|key| key.include?(word)}
    matches.map {|match| @data[match] }
  end      
end

p search ['of'] #=> [[["1.txt", "2.txt"]]]
p search ['one'] #=> [[["1.txt"]]]
p search ['on']  #=> [[["1.txt", "2.txt"], ["1.txt"]]] - note that "contents" contains "on" 

关于Ruby:在倒排索引中搜索部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951892/

相关文章:

ruby - 如何连续循环另一个循环中的数组值?

postgresql - PostgreSQL 中的查询扩展

mysql - 全文 : this query very slow

full-text-search - Google Sites API 全文搜索不适用于非西方语言

MySQL 5.1,全文搜索没有找到单词 "more"

ruby - 在方法参数上映射 splat 参数

javascript - 如何执行复杂的Javascript代码?

ruby-on-rails - Rails 返回 500 错误(不确定原因)

Ruby define_method 问题

full-text-search - ElasticSearch——有没有办法检索多个结果集或 fasset 的热门结果?