Skip to content
Advertisement

PostgreSQL create index on JSONB[]

Consider a table defined as follows:

How can I create an index on json key type and how can I query on it?

Edit: Previously, there were no indexes on json keys and select queries used an unnest operation as shown below:

The problem is, if the table has a large number of rows, the above query will not only include a full table scan, but also filtering through each jsonb array.

Advertisement

Answer

There is a way to index this, not sure how fast it will be.

If that was a “regular” jsonb column, you could use a condition like where tag_counts @> '[{"type": 2}]' which can use a GIN index on the column.

You can use that operator if you convert the array to “plain” json value:

Unfortunately, to_jsonb() is not marked as immutable (I guess because of potential timestamp conversion in there) which is a requirement if you want to use an expression in an index.

But for your data, this is indeed immutable, so we can create a little wrapper function:

And with that function we can create an index:

You will need to use that function in your query:

On a table with a million rows, I get the following execution plan:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement