PostgreSQL中表达式索引的实际限制

时间:2011-06-07 11:31:02

标签: sql database-design postgresql expression indexing

我需要使用HSTORE类型和按键索引来存储数据。

CREATE INDEX ix_product_size ON product(((data->'Size')::INT))
CREATE INDEX ix_product_color ON product(((data->'Color')))
etc.

使用表达式索引有哪些实际限制?在我的例子中,可能有数百种不同类型的数据,因此有数百个表达式索引。每个insert,update和select查询都必须处理这些索引才能选择正确的索引。

1 个答案:

答案 0 :(得分:4)

我从未玩过hstore,但是当我需要EAV专栏时,我会做类似的事情,例如:

create index on product_eav (eav_value) where (eav_type = 'int');

这样做的限制是您需要在查询中明确使用它,即此查询不会使用上述索引:

select product_id
from product_eav
where eav_name = 'size'
and eav_value = :size;

但是这个会:

select product_id
from product_eav
where eav_name = 'size'
and eav_value = :size
and type = 'int';

在你的例子中,它可能更像是:

create index on product ((data->'size')::int) where (data->'size' is not null);

这应该避免在没有大小条目时添加对索引的引用。根据您使用的PG版本,可能需要修改查询:

select product_id
from products
where data->'size' is not null
and data->'size' = :size;

常规索引和部分索引之间的另一个重要区别是后者无法在表定义中强制执行唯一约束。这将成功:

create unique index foo_bar_key on foo (bar) where (cond);

以下不会:

alter table foo add constraint foo_bar_key unique (bar) where (cond);

但这会:

alter table foo add constraint foo_bar_excl exclude (bar with =) where (cond);
相关问题