Question
How can you make a PostgreSQL View based on a JSONB field object array, with appropriate indexes? Example below.
- Conceptually, how should indexing be applied when using with Views and a JSONB array?
- What is the correct syntax to create the relevant indexes?
- Is the example view given the correct/optimal way to construct the view for this use case?
Example
Table
CREATE TABLE "ProductLists"
(
id uuid NOT NULL DEFAULT gen_random_uuid(),
listName text NOT NULL
productIds jsonb NOT NULL DEFAULT '[{ productId:0 }]'::jsonb,
)
View (can be changed)
With the following view:
SELECT "ProductLists".id AS listId,
jsonb_array_elements("ProductLists".productIds) ->> 'productId'::text AS productId
FROM "ProductLists";
Factors
- The JSONB Root is an array, not an object (which is not the case in most indexing examples)
- There will be potentially millions of ProductList items
- The number of productIds in each list will usually be less than 100
- The table will have both high reads and writes
- The view SQL example may or may not be optimal for the purpose, and can be changed
Thanks for any input!
listOrdervalue in 100's of rows. I am looking at using the JSONB field to avoid this. One ordered list, neatly stored in a single field.