微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

解决方法

我从来没有玩过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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐