Postgresql 索引jsonb数组和查询jsonb数组

Postgresql 索引jsonb数组和查询jsonb数组,postgresql,indexing,jsonb,postgresql-9.6,Postgresql,Indexing,Jsonb,Postgresql 9.6,我需要让这个查询使用indexeson jsonb列products\u rec\u jsonb,比如products、categoryid和id 我想将产品和类别id作为GIN索引,将id作为BTREE DESC索引作为bigint数据类型…问题是,当我运行查询时,它根本不使用索引。我如何修复它?您的查询不会使用您的索引,因为您使用jsonb\U数组元素手动解开JSON数组。-如果您重构查询以使用包含运算符,则查询的某些部分可能会在整个products\u rec\u jsonb列上使用一个G

我需要让这个查询使用indexeson jsonb列products\u rec\u jsonb,比如products、categoryid和id


我想将产品和类别id作为GIN索引,将id作为BTREE DESC索引作为bigint数据类型…问题是,当我运行查询时,它根本不使用索引。我如何修复它?

您的查询不会使用您的索引,因为您使用jsonb\U数组元素手动解开JSON数组。-如果您重构查询以使用包含运算符,则查询的某些部分可能会在整个products\u rec\u jsonb列上使用一个GIN索引,即。尽管如此,这些部分,如WHERE elem->>“id”::bigint<1234和ORDER BY elem->>“id”::bigint将永远无法使用GIN进行索引。感谢您的回答……我特别需要对“id”进行索引:这真的不可能吗?根据您当前的模式,确实不可能。您可以重新设计表,使其具有与原始表具有一对多关系的连接表,该连接表可以容纳JSON数组元素,而不是完整的数组。那将是可索引的。听起来是个不错的选择。。。
[{"id": "345", "categoryid": "2", "products": ["23", "45","34"]}]
[{"id": "2343", "categoryid": "3", "products":  ["123", "455"]}]
[{"id": "12", "categoryid": "12", "products":  ["234", "459","314","4563"]}, {"id": "512", "categoryid": "15", "products":  ["234"]}]
[{"id": "123", "categoryid": "3", "products":  ["293", "145","634"]}, {"id": "889", "categoryid": "18", "products":  ["123", "845","1234"]}]
[{"id": "2546", "categoryid": "2", "products":  ["2397", "452","434","234", "479","304","4563"]}]


SELECT *
FROM   products p,
       jsonb_array_elements(p.products_rec_jsonb) elem
WHERE  (elem ->> 'id')::bigint < 1234
       AND
       (
         (
           (elem -> 'products') ?| array(12,576,34)::text[]
           AND
           (elem -> 'categoryid') ?| array(12,5)::text[]
         )
         OR
         (elem -> 'categoryid') ?| array(12,5)::text[]
       )
ORDER BY (elem ->> 'id')::bigint DESC
LIMIT 20;

CREATE INDEX CONCURRENTLY idx_products_products ON products  USING GIN (products_rec_jsonb -> 'products')  

CREATE INDEX CONCURRENTLY idx_products_category ON products  USING GIN (products_rec_jsonb -> 'categoryid')  

CREATE INDEX CONCURRENTLY idx_products_id ON products  USING BTREE (products_rec_jsonb ->> 'id')