-- 1. DDL for event_logs table CREATE TABLE event_logs ( id SERIAL PRIMARY KEY, timestamp TIMESTAMPTZ DEFAULT NOW(), payload JSONB );
-- 2. Sample INSERT statements INSERT INTO event_logs (payload) VALUES ('{"type": "user_action", "details": {"user_id": 101, "action": "login", "status": "success"}}'), ('{"type": "system_event", "details": {"component": "auth", "message": "token_refresh", "status": "completed"}}'), ('{"type": "user_action", "details": {"user_id": 102, "action": "view_product", "status": "pending"}}'), ('{"type": "error_log", "message": "database_connection_failed", "severity": "high"}'), ('{"type": "user_action", "details": {"user_id": 101, "action": "add_to_cart", "status": "success"}}');
-- 3. Filtering Query 1 (Exact Match) SELECT id, timestamp, payload FROM event_logs WHERE payload->>'type' = 'user_action';
-- 4. Expected Query Plan Notes 1 Without an index, this query would perform a Seq Scan over the entire event_logs table, reading every row to extract and compare the 'type' field. With the recommended GIN index on payload, the query plan would show an Index Scan or Bitmap Index Scan, allowing PostgreSQL to quickly locate matching rows without a full table scan, significantly improving speed.
-- 5. Filtering Query 2 (Nested Field Match) SELECT id, timestamp, payload FROM event_logs WHERE payload->'details'->>'status' = 'completed';
-- 6. Expected Query Plan Notes 2 Similar to Query 1, an unindexed query would result in a Seq Scan, iterating through all rows to navigate and compare the nested status field. With the GIN index, the query plan would again show an Index Scan. The jsonb_path_ops operator class is designed to efficiently handle queries involving nested JSONB fields, directly finding entries where payload->'details'->>'status' matches, avoiding full table scans.
-- 7. GIN Index Recommendation CREATE INDEX idx_event_logs_payload_gin ON event_logs USING GIN (payload jsonb_path_ops);
Explanation: The GIN (Generalized Inverted Index) is highly effective for indexing JSONB data, particularly for queries that check for specific key-value pairs or path-based lookups. The jsonb_path_ops operator class is recommended as it indexes the *paths* and *values* within the JSONB document. This makes it ideal for queries using the -> and ->> operators for specific key-value pairs or nested paths, such as payload->>'type' or payload->'details'->>'status'. This provides better performance for these types of equality checks compared to the default jsonb_ops which indexes all keys and values but might be less efficient for path-specific queries.
-- 8. Update Query (Nested Field) UPDATE event_logs SET payload = jsonb_set(payload, '{details,status}', '"processed"', false) WHERE id = 3;
-- 9. Verification Query SELECT id, payload->'details'->>'status' AS new_status FROM event_logs WHERE id = 3;