使用 STI 时索引去哪里?
我正在使用 Rails 和 postgres。
我有几个使用 STI 的模型,我想知道应该将索引放在表的哪里,为什么?
例如,假设我有以下设置:
class Comment < AR; end
class MovieComment < Comment; end
class MagazineComment < Comment; end
# Fake Comment Table
id:integer
title:string
body:text
type:string
谢谢!
I am using Rails and postgres.
I have a couple of models using STI and i was wondering where i should put indexes on the tables and why?
For example lets say i have the following setup:
class Comment < AR; end
class MovieComment < Comment; end
class MagazineComment < Comment; end
# Fake Comment Table
id:integer
title:string
body:text
type:string
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只需要
MovieComment
或MagazineComment
之一,请在type
字段上。如果您不这样做,则此处不需要索引。我不确定 AR 是否每次都使用type
,但只是为了确定一下。因为 id 字段是主键,所以索引应该已经存在。
如果您想同时通过
type
和id
进行查询,请确保您有一个组合索引。在其他字段上:取决于您查询的内容,但我想您只想检索这些字段。
On the
type
field, if you want only one ofMovieComment
orMagazineComment
. If you don't do that, you won't need the index here. I'm not sure if AR does usetype
every time, but just to make sure.Because the
id
field is a primary key, an index should already be there.If you want to query by both
type
andid
make sure you have a combined index.On the other fields: Depends what you query on, but I suppose you want to retrieve these only.
一般来说,您需要在执行查询时使用的列中建立索引。
如果您执行
MovieComment.find(10)
,数据库将使用 Rails 自动为您添加的id
字段中的索引。如果你这样做Comment.find(30)
也是如此:Rails 将使用索引检索id
30 的command,然后它将读取type
列,它将返回一个MovieComment
或MagazineComment
。例如,如果您要添加按标题搜索的功能,则还必须在此列中创建索引。在本例中,可能是一个 :fulltext 索引。
type
列中的索引将使像MagazineComment.all
这样的查询更快,因为它相当于Comment.where(type: 'MagazineComment').all< /code>,但这可能不值得。
In general, you need indices in the columns that you will use when performing queries.
If you do
MovieComment.find(10)
, the database will use the index in theid
field that Rails will add automatically for you. Same if you doComment.find(30)
: Rails will retrieve the commend withid
30 using the index, then it will read thetype
column and it will return aMovieComment
or aMagazineComment
.If you are going to add a feature to search by title, for instance, you will have to create an index in this column as well. In this case, probably a :fulltext index.
An Index in the
type
column would make a query likeMagazineComment.all
faster because it is equivalent toComment.where(type: 'MagazineComment').all
, but it is probably not worth it.