【问题标题】:Add index with sort order?使用排序顺序添加索引?
【发布时间】:2013-06-03 14:32:34
【问题描述】:

在 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

【问题讨论】:

  • 你检查过API here吗?它具有“创建具有排序顺序的索引”

标签: ruby-on-rails postgresql indexing migration


【解决方案1】:

Rails 现在支持在迁移中指定索引顺序:

def change
  add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
end

来自http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

【讨论】:

    【解决方案2】:

    您不需要在索引中指定DESC。对于使用这种特定排序的查询,它会带来一点速度优势,但总的来说 - 索引可用于列的任何排序。

    【讨论】:

    • 如果 ORDER BY 类似于​​ kind asc, itunes_release_date desc,则不完全正确。这真的取决于查询。
    • @MarkusWinand:没错,但 OP 的特定查询适合无关紧要的场景:where kind = ... order by itunes_release_date。
    【解决方案3】:

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

    我怀疑您可以安全地删除两个desc,顺便说一句:kind 在您的 where 子句中,基于您之前的问题,所以 PG 应该很乐意以相反的顺序查找索引。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2018-08-25
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多