我們有一個Postgres數據庫,它通過一個節點應用程序進行填充,該應用程序解析XML併爲我們加載我們的數據集。Postgres - 如何直接創建索引(在activerecord之外)?
我們構建了一個Sinatra應用程序來查看數據。我們有一個archive_objects
其中有tags
號碼。
我們已經通過他們的模型相關的兩個類,如:
class ArchiveObject < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :archive_objects
end
我們注意到,調用,例如current_archive_object.tags
是相當緩慢的(平均400個+ MS),閱讀Using indexes in rails: Index your associations後,我看到建議建立在ActiveRecord的遷移這個簡單的關聯指數(修改相關的名字在這裏):
add_index :tags, :archive_object_id, :name => 'archive_object_id_idx'
我想知道,我怎麼能直接在psql
中創建這個索引,因爲我們的數據庫不是通過AR遷移生成的?
編輯: 對我們的 '結表' 信息,它應該是相關
\d+ archive_objects_tags
Table "public.archive_objects_tags"
Column | Type | Modifiers | Storage | Stats target | Description
-------------------+--------------------------+-----------+---------+--------------+-------------
created_at | timestamp with time zone | not null | plain | |
updated_at | timestamp with time zone | not null | plain | |
tag_id | integer | not null | plain | |
archive_object_id | integer | not null | plain | |
Indexes:
"archive_objects_tags_pkey" PRIMARY KEY, btree (tag_id, archive_object_id)
Has OIDs: no
從機架控制檯SQL調用:
Tag Load (397.4ms) SELECT "tags".* FROM "tags" INNER JOIN "archive_objects_tags" ON "tags"."id" = "archive_objects_tags"."tag_id" WHERE "archive_objects_tags"."archive_object_id" = $1 [["archive_object_id", 4823]]
您可以創建一個遷移來添加索引。例如在遷移中 'def change' 'add_index:table,:column_to_be_indexed' 'end' –