My pg is 9.5+. I have a jsonb data in column 'body':
{
"id":"58cf96481ebf47eba351db3b",
"JobName":"test",
"JobDomain":"SAW",
"JobStatus":"TRIGGERED",
"JobActivity":"ACTIVE"
}
And I create index for body and key:
CREATE INDEX scheduledjob_request_id_idx ON "ScheduledJob" USING gin ((body -> 'JobName'));
CREATE INDEX test_index ON "ScheduledJob" USING gin (body jsonb_path_ops)
This are my queries:
SELECT body FROM "ScheduledJob" WHERE body @> '{"JobName": "analytics_import_transaction_job"}';
SELECT body FROM "ScheduledJob" WHERE (body#>'{JobName}' = '"analytics_import_transaction_job"') LIMIT 10;
Those are return correct data, but no one use index. I saw the explain:
-> Seq Scan on public."ScheduledJob" (cost=0.00..4.55 rows=1 width=532)
So, I don't know why didn't use the index, and how to use the index for jsonb correctly.
Update:
- I create index before insert data, the query can use index.
- But I create index after insert the first data, the query will be scan all records.
This is so strange, and how can I make the index useful when I insert data first.
body#>'{JobName}'will never use an index of(body -> 'JobName'). Use the same expression (i.e. the same operator) to have at least a chance. -- Please postEXPLAIN ANALYZEof your queries. Your table may not contain enough sample rows to use an index.INDEX ON "ScheduledJob" USING btree ((body ->> 'JobName')).