Skip to content

Conversation

@SvetlinZarev
Copy link
Contributor

Replace the unused GIN index with a BTREE index when searching by price, because the -> operator is not accelerated by the GIN index.

Each index in PG supports only specific "operator classes" (see https://www.postgresql.org/docs/current/gin.html#GIN-BUILTIN-OPCLASSES) . When working with JSONB, GIN has two modes:

  • jsonb_ops (default), which supports the ?, ?|, ?&``@>, @?,@@,, etc operators
  • jsonb_path_ops, which is smaller and faster, but supports only @>, @? and @@

Notice that none of those support ->, which means that the GIN index will not be used when filtering by jsonb -> 'price'. The gin is great only for "contains" type of operations.

In order to fix that, I replace the GIN, which indexes the whole JSON body, with a BTREE, which indexes only the property we are interested in. This should improve insterts/updates/deletes, as the index is smaller and faster to create/update. Also it will speed-up searches, because now the query will use the index to filter by price.

…ce, because the `->` operator is not accelerated by the GIN index
Copy link
Owner

@antonputra antonputra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @SvetlinZarev, I realized only after I ran this test. Good catch!

@antonputra antonputra merged commit bf80fe9 into antonputra:main Nov 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants