搜索结果并对其进行排名

发布于 2024-08-05 12:49:39 字数 933 浏览 1 评论 0原文

我正在尝试编写一个相对简单的算法来搜索多个属性上的字符串

给定一些数据:

一些数据:

1: name: 'Josh', location: 'los angeles'
2: name: 'Josh', location: 'york'

搜索字符串:“josh york”

结果应该是 [2, 1] 因为查询字符串命中第二条记录两次,命中第一条记录一次。

在这里假设不区分大小写是安全的。

到目前为止,这是我在 ruby​​/active record 中所得到的:

query_string = "josh new york"
some_attributes = [:name, :location]

results = {}
query_string.downcase.split.each do |query_part|
  some_attributes.each do |attribute|
    find(:all, :conditions => ["#{attribute} like ?", "%#{query_part}%"]).each do |result|
      if results[result]
        results[result] += 1
      else
        results[result] = 1
      end
    end
  end
end

results.sort{|a,b| b[1]<=>a[1]}

我使用此方法的问题是它会产生大量查询(query_string.split.length * some_attributes.length)。

我可以通过减少查询数量来提高效率吗?

我可以接受在 ruby​​ 中进行排序,不过如果能以某种方式将其塞入 SQL 中那就太好了。

I'm trying to write a relatively simple algorithm to search for a string on several attributes

Given some data:

Some data:

1: name: 'Josh', location: 'los angeles'
2: name: 'Josh', location: 'york'

search string: "josh york"

The results should be [2, 1] because that query string hits the 2nd record twice, and the 1st record once.

It's safe to assume case-insensitivity here.

So here's what I have so far, in ruby/active record:

query_string = "josh new york"
some_attributes = [:name, :location]

results = {}
query_string.downcase.split.each do |query_part|
  some_attributes.each do |attribute|
    find(:all, :conditions => ["#{attribute} like ?", "%#{query_part}%"]).each do |result|
      if results[result]
        results[result] += 1
      else
        results[result] = 1
      end
    end
  end
end

results.sort{|a,b| b[1]<=>a[1]}

The issue I have with this method is that it produces a large number of queries (query_string.split.length * some_attributes.length).

Can I make this more efficient somehow by reducing the number of queries ?

I'm okay with sorting within ruby, although if that can somehow be jammed into the SQL that'd be nice too.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟酉 2024-08-12 12:49:39

你为什么不使用像 Ferret 这样的东西? Ferret 是一个用于制作全文索引的 Ruby + C 扩展。由于您似乎使用的是 ActiveRecord,因此还有 acts_as_ferret

Why aren't you using something like Ferret? Ferret is a Ruby + C extension to make a full text index. Since you seem to be using ActiveRecord, there's also acts_as_ferret.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文