如何在Postgres 中使用帶有JSONB 數組的GIN 索引
問題:
Postgres 12 或的正確索引稍後:
CREATE INDEX locations_events_gin_idx ON locations USING gin (events jsonb_path_ops);
Postgres 12 或更高版本的查詢語法:
SELECT * FROM locations WHERE events @? '$[*] ? (@.event_slug == "test_1") ? (@.end_time.datetime() < "2014-10-13".datetime()'
舊版Postgres 的查詢語法:
SELECT * FROM locations WHERE events @> '[{ "event_slug": "test_1"}]';
使用物化視圖的高階解決方案:
CREATE MATERIALIZED VIEW loc_event AS SELECT l.location_id, e.event_slug, e.end_time -- start_time not needed FROM locations l, jsonb_populate_recordset(null::event_type, l.events) e; CREATE INDEX loc_event_idx ON loc_event (event_slug, end_time, location_id);
物化視圖查詢:
SELECT * FROM loc_event WHERE event_slug = 'test_1' AND end_time >= '2014-10-30 14:04:06 -0400'::timestamptz;
以上是如何使用 GIN 索引最佳化 Postgres JSONB 陣列查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!