Skip to content
Advertisement

Speed up query on JSONB object field Postgres / indexing a JSONB field

I am trying to speed up queries on an object field in Postgres.

The table I am searching has the following structure:

  • page_id: integer
  • lang: varchar(2)
  • images: jsonb

The images JSONB field contains objects like this:

I need to retrieve all pages that use a certain file – which I do like so:

It works ok but it’s dead slow – query plan is like this:

I am thinking that indexing on the object field, and I’ve read up a bit on indexing on object, but can’t find something about indexing on fields of fields.

I have thought about normalizing into another table as an alternative strategy, but I’d like to avoid that (keeping things in sync etc is a bit of a burden).

Any ideas?

Advertisement

Answer

You can’t do this with the normal jsonb index methods, as they don’t let you index into object values without specifying the keys leading to them.

You can use a helper function which converts your JSONB to an array of values.

Note that I didn’t preserve the unnesting in your query, because I don’t know to what extent you wanted the unnested results, versus just doing the unnesting to provide a way to get at the correct row. You might need to filter on ‘File:Vigoleno castello2.jpg’ twice, once to get the correct row via the index, and once more to get the correct element from within the row.

There are many other variations on this theme. You could use the helper function to return a JSONB with an array of titles, rather than a text[]. Or you could make it return a JSONB of an array of objects, rather than an object of objects. If you did that, you could use @> to query into that array of objects.

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