我正在使用 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
谢谢!
我正在使用 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
谢谢!
在type
球场上,如果您只想要一个MovieComment
或MagazineComment
。如果你不这样做,你就不需要这里的索引。我不确定AR是否type
每次都使用,但只是为了确定。
因为该id
字段是主键,所以索引应该已经存在。
如果您想同时查询type
并id
确保您有一个组合索引。
在其他字段上:取决于您查询的内容,但我想您只想检索这些。
通常,您需要在执行查询时使用的列中的索引。
如果你这样做MovieComment.find(10)
,数据库将使用id
Rails 自动为你添加的字段中的索引。如果你这样做也一样Comment.find(30)
:Rails 将id
使用索引检索 30 的推荐,然后它将读取该type
列并返回 aMovieComment
或 a MagazineComment
。
例如,如果您要添加一个按标题搜索的功能,您还必须在此列中创建一个索引。在这种情况下,可能是一个:fulltext索引。
列中的索引type
会使查询MagazineComment.all
更快,因为它相当于Comment.where(type: 'MagazineComment').all
,但它可能不值得。