【问题标题】:Should I use a LIKE query for these ActiveRecord relationships?我应该对这些 ActiveRecord 关系使用 LIKE 查询吗?
【发布时间】:2016-09-04 09:22:01
【问题描述】:

假设我有一个带有 2 组复选框的网页表单用户界面。使用第 1 组复选框,我可以勾选我想要的训练师(“Jason”、“Alexandra 等)。使用第 2 组复选框,我可以勾选我想要看到的动物(“老虎”、“熊”、等等)一旦我提交了带有这些选项的表格,我会返回一个符合标准的动物园列表(假设所有的培训师都在所有的动物园工作,所有的动物都在所有的动物园里,以便讨论)

我们将通过“名称”运行我们的数据库查询(例如,使用训练师名称和动物名称进行搜索,而不是数据库 ID)

假设我们正在使用具有数十万行(如果不是数百万行)的 Postgres 数据库。

  1. 使用“ILIKE”查询搜索效率更高还是使用标准连接查询更好(例如,Zoo.includes(:animals, :trainers).where("animals.name = ? and trainers.name = ?", animal_names, trainer_names)
  2. 有没有比我刚才在上面 #1 中展示的更好的方法?

模型设置

class Zoo < ActiveRecord::Base 
  has_many :animals, through: zoo_animals
  has_many :trainers, through: zoo_trainers
  has_many :zoo_trainers
  has_many :zoo_animals
end  

class Animal < ActiveRecord::Base
  has_many :zoos, through :zoo_animals
  has_many :zoo_animals
end  

class Trainer < ActiveRecord::Base
  has_many :zoos, through :zoo_trainers 
  has_many :zoo_trainers
end  

class ZooAnimal < ActiveRecord::Base
  belongs_to :animal
  belongs_to :zoo
end

class ZooTrainer < ActiveRecord::Base
  belongs_to :zoo
  belongs_to :trainer
end

编辑:假设我无权访问数据库 ID。

【问题讨论】:

  • 为什么不从表单中返回 ID?
  • 好点,假设我也可以这样做。
  • 但我仍然想回答这个问题 - 假设我无权访问数据库 ID。
  • 您需要什么LIKEILIKE 查询?您是要搜索“%Jason%”还是“Jason%”还是只搜索“Jason”或其他内容?
  • Both - 基本上是任何包含子字符串“Jason”的选项

标签: ruby-on-rails ruby postgresql rails-activerecord


【解决方案1】:

LIKE '%Jason%' 比查询确切的字符串“Jason”(或查询 ID)效率低得多,因为虽然 LIKE 的精确比较和某些用途可以在被查询的列上使用索引,但 @987654321 @。

但是,性能听起来并不是这里最重要的考虑因素。 LIKE %Jason% 在合理负载下的合理大小的数据库上可能仍然足够快。如果应用程序确实需要通过子字符串搜索事物(这意味着搜索可能有多个结果),那么简单的相等就无法满足该要求。

搜索文本的功能更强大的解决方案数不胜数,包括 Postgres 内置的全文搜索和 Elasticsearch 等外部解决方案。如果没有具体的扩展要求,我会选择LIKE,直到它开始放缓,然后才投资更复杂的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 2013-03-09
    • 2013-02-04
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多