大型数据库中的高级搜索轨道



我有一个非常大的数据库,我使用类似于这个railscast的高级搜索表单:http://railscasts.com/episodes/111-advanced-search-form-revised

也许这是一个愚蠢的问题,但想象一下,你有400000个(或更多)产品,你正在用这个.where(和分页)链进行过滤。

products = Product.order(:name)
products = products.where("name like ?", "%#{keywords}%") if keywords.present?
products = products.where(category_id: category_id) if category_id.present?
products = products.where("price >= ?", min_price) if min_price.present?
products = products.where("price <= ?", max_price) if max_price.present?
products.page(params[:page])

在我看来,搜索执行第一个条件,然后与其他where条件一起过滤,这样就可以搜索到400000个产品。这不会扼杀表演吗,还是我完全(我希望)错了?

注意:我也在railscast上写过这个问题,但作为一名老railscast,我不知道是否有人会在那里看到这个问题。出于这个原因,我也在这里写作。

只需从表单中的参数中使用哈希,我已经有一段时间没有这样做了,我甚至没有代码了,但理论上应该是这样的:

finder = Hash.new
params[:form].each {|index, val|
finder[index] = val
}

它将创建一个已传递的所有参数的哈希,您可以像这样将其传递给活动记录搜索。

products = Products.where(finder)

Rails将把所有这些.where条件组合到一个SQL查询中。

如果你的数据库被正确地索引,那么你应该没事。

最新更新