Indexes on PostgreSQL hstore array columns

ε祈祈猫儿з 提交于 2019-11-30 16:04:55

I think you've misunderstood PostgreSQL Arrays. An Array is actually just a string. You can't index the objects (in this case HSTOREs) in the array, simply because it's not a TABLE.

Instead, create an extra table:

CREATE TABLE customer (
    pk bigserial PRIMARY KEY,
    customer hstore
);

CREATE TABLE purchases (
    pk bigserial PRIMARY KEY,
    customer_pk bigint not null,
    purchase hstore not null,
    constraint "must be a valid customer!" 
        foreign key (customer_pk) references customer(pk)
);

Also, Why are you using HSTOREs here?

If you must create an INDEX based on the "purchase" HSTORE here, do something like this:

CREATE OR REPLACE FUNCTION purchase_amount(purchase hstore) returns float as $$
    select ($1 -> 'price')::float;
$$ language 'SQL' IMMUTABLE;

CREATE INDEX "purchases by price" ON purchases (purchase_amount(purchase));

Is this just an exercise to understand the HSTORE type? or do you have some real use case that would make all this obfuscation of your real data worthwhile?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!