2013-06-03 76 views
1

在Rails中,如何在具有特定排序顺序的Postgres数据库迁移中添加索引?按排序顺序添加索引?

最终想拉断此查询:

CREATE INDEX index_apps_kind_release_date_rating ON apps(kind, itunes_release_date DESC, rating_count DESC); 

但是现在在我的移民我有这样的:

add_index :apps, [:kind, 'itunes_release_date desc', 'rating_count desc'], name: 'index_apps_kind_release_date_rating' 

哪个吐出了这一点:

CREATE INDEX "index_apps_kind_release_date_rating" ON "apps" ("kind", "itunes_release_date desc", "rating_count desc") 

哪些错误出:

PG::Error: ERROR: column "itunes_release_date desc" does not exist 
+0

你有[这里API]检查(http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/ add_index)?它具有“按排序顺序创建索引” – konyak

回答

2

看起来像Rails不支持有序索引。

我怀疑你可以安全地删除这两个desc,btw:kind基于你以前的问题在你的where子句中,所以PG应该愉快地按照相反的顺序查找索引。

+0

Postgres可以按相反顺序查找索引,但速度稍慢。 –

+0

Rails版本4.2.7实际上。通过https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index查找语法。搜索':desc' – fatuhoku

3

您不需要在索引中指定DESC。它会为查询提供一个小的速度优势,它使用这个特定的顺序,但通常 - 索引可以用于任何列的列表。

+0

如果ORDER BY类似'kind asc,itunes_release_date desc',那么这并不完全正确。这真的取决于查询。 –

+0

@MarkusWinand:这是正确的,但是OP的特定查询适合于无关紧要的场景:'where kind = ... by itunes_release_date'。 –