0

过去几天我一直在做一些关于索引的大量阅读,我试图找出正确的方法来索引我有很多限制的查询。我正在使用postgres_ext gem来支持数组数据类型以及 GIN 和 GIST 索引类型。

我有两个疑问

.where("a_id IN (?) and b = ? and active = ? and ? != ALL(c) and ? = ANY(d)")
.where("a_id =? and active =? and ? != ALL(c)")

c 和 d 是整数数组

我计划添加的索引:

 add_index :deals, [:a, :b], :where => "active = true"
 add_index :deals [:c, :d], :index_type => :gin, :where => "active = true"

postgres 会在第一个查询中使用这两个多列索引吗?

数组数据类型是否应该始终采用“gin”索引类型?或者你也可以把它们放在 b-tree 索引中吗?

最后,第一个索引是否会在两个查询中用于“a”?

附加信息:

我正在使用 PostgreSQL 9.1.3

create_table "table", :force => true do |t|
 t.integer  "a_id"    ##foreign key
 t.string   "title"
 t.text     "description",    :default => ""
 t.boolean  "active",           :default => true
 t.datetime "created_at",      :null => false
 t.datetime "updated_at",    :null => false
 t.integer  "b",
 t.integer  "c", :limit => 8,   :array => true
 t.integer  "d",  :array => true
end
4

1 回答 1

4

关于数组和 GIN,您可以拥有数组的 b-tree 索引,但它对于“数组包含元素”之类的操作没有用。为此,您需要 GIN 或 GiST,并且仅支持 GIN 作为所有数组类型的内置索引。

您还可以将intarray扩展及其 GiST 索引类型用于整数数组,这些数组在写入负载下性能更好,但在读取负载下性能更差。

至于Pg是否会使用这两个索引,最好的判断方法是使用EXPLAIN ANALYZE和查看。log_statement通过启用或从带有 SQL 登录的 Rails 日志中获取 Rails 从 PostgreSQL 日志中执行的语句。然后psqlexplain analyze. 或者,使用auto_explain扩展在查询运行时捕获性能报告。

I have the feeling that you'll find that Pg can't combine a GiST or GIN and a b-tree index in the same filter. Combining indexes requires a bitmap index scan and that's IIRC only available for two b-tree indexes. You'd probably need to add the extra columns to the GiST or GIN index, but that'll increase the index size quite dramatically and may not be worth it.

You really need to use explain analyze to see how it works in the real world on sample or production data.

When working with multicolumn indexes, keep in mind that at least for b-tree indexes Pg can use an index on (a,b) for queries that filter on a or on both a and b, but not for queries that filter only on b. Indexes are usable left-to-right, you can't use an index to search for a value on the right side of the index unless you're also searching on all values to the left of it.

于 2013-03-09T01:58:04.823 回答