I have a PostgreSQL table named item_log
with a log
column of type jsonb
that contains various attributes. One of these attributes is delete_log
. I'm querying this table based on the created_at
field and the presence of non-null
values in the delete_log
attribute.
SELECT item_id
FROM item_log
WHERE created_at >= CURRENT_DATE - INTERVAL '15 days'
AND (log->>'delete_log') IS NOT NULL;
I'm considering different indexing strategies for optimizing my queries:
Here is what I have tried,
Created index on created_at
: Query became faster when I didn't put the condition
(log->>'delete_log') IS NOT NULL
in the query which is expected.
As soon as I put this condition or even select this field it took around 40 minutes.
I guess that the query slowdown occurs due to the inclusion of delete_log
. When this field is queried, it starts reading the TOAST
table and performs deTOAST
operations, which increases I/O time significantly.
Now to optimize the query I have a couple of options:
- Add composite index on
(created_at, log->>delete_log)
- Add index on
(log->>delete_log)
as I already have index oncreated_at
?
Also, I have another confusion.
- What index type should I choose for
log->>delete_log
? - And, How is it different from indexing the whole
log
field itself in terms of performance or storage for the above query?