简体   繁体   English

使用Rails app进行数据库索引

[英]Database Indexing with Rails app

I have the tables: Products, Sub_Categories and Categories. 我有表:产品,Sub_Categories和类别。 Categories has many Sub_Categories, Sub_Categories belongs_to Categories and has many products and product belongs to sub_categories. 类别有许多Sub_Categories,Sub_Categories属于_to Categories并且有许多产品和产品属于sub_categories。 My products table has a sub_category_id; 我的产品表有一个sub_category_id; my sub_category table has a category_id. 我的sub_category表有一个category_id。 What would be the most efficient way to index these tables to increase the app load time? 索引这些表以增加应用程序加载时间的最有效方法是什么?

Without any more info, for better access times for your queries, you would index these: 如果没有更多信息,为了更好地查询您的查询,您可以将这些信息编入索引:

categories on id
subcategories on id
subcategories on category_id
product on id
product on sub_category_id

You might also use eager loading. 您也可以使用预先加载。 For example, if you are going to need a category and several subcategories, load everything in fewer db queries with 例如,如果您需要一个类别和几个子类别,请使用更少的数据库查询加载所有内容

Category.includes(:sub_categories).find(:id)

. See http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations . 请参阅http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

Anil's answer is correct, but as he intimates, your question is too vague. Anil的答案是正确的,但正如他暗示的那样,你的问题太模糊了。 I would suggest turning on query logging, and seeing which queries are taking up time in page loading. 我建议启用查询日志记录,并查看哪些查询占用了页面加载的时间。 Then take the offending queries, and type EXPLAIN {query} into a mysql prompt (which you can reach using rails dbconsole or the standalone mysql client provided by Oracle). 然后执行有问题的查询,并将EXPLAIN {query}键入mysql提示符(可以使用rails dbconsole或Oracle提供的独立mysql客户端访问)。 Look at the indices used in the bottleneck queries, and ask a more specific question. 查看瓶颈查询中使用的索引,并询问更具体的问题。

I'm guessing that a lot of your queries are querying for products by their category ID. 我猜你的很多查询都是按类别ID查询产品。 Adding an indexed category_id column to Products might speed things up by avoiding a join, though then the onus on you to keep that column up-to-date. 向产品添加索引的category_id列可能会通过避免加入来加快速度,但是您有责任使该列保持最新状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM