-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05.json-jsonb.sql
More file actions
262 lines (204 loc) · 7.24 KB
/
05.json-jsonb.sql
File metadata and controls
262 lines (204 loc) · 7.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
-- =====================================================
-- Create Table
-- =====================================================
DROP TABLE IF EXISTS customer_events;
CREATE TABLE customer_events
(
id BIGSERIAL PRIMARY KEY,
customer_id INT,
event_data JSONB,
created_at TIMESTAMP DEFAULT now()
);
-- =====================================================
-- Generate Large Dataset (10,000 Rows)
-- Each customer gets multiple events
-- =====================================================
INSERT INTO customer_events (customer_id, event_data)
SELECT (random() * 1000)::INT AS customer_id,
jsonb_build_object(
'event_type',
(ARRAY ['login','logout','purchase','view','cart_add'])
[floor(random() * 5 + 1)],
'device',
(ARRAY ['mobile','desktop','tablet'])
[floor(random() * 3 + 1)],
'amount',
CASE
WHEN random() > 0.5
THEN (random() * 1000)::INT
ELSE NULL
END,
'location',
(ARRAY ['EU','US','APAC'])
[floor(random() * 3 + 1)],
'metadata',
jsonb_build_object(
'ip', '192.168.' || (random() * 255)::INT || '.' || (random() * 255)::INT,
'browser',
(ARRAY ['chrome','firefox','safari','edge'])
[floor(random() * 4 + 1)]
)
) AS event_data
FROM generate_series(1, 10000);
-- =====================================================
-- Basic JSON Query
-- =====================================================
SELECT event_data ->> 'event_type' AS event_type,
COUNT(*)
FROM customer_events
GROUP BY event_type
ORDER BY COUNT(*) DESC;
-- =====================================================
-- Filter JSONB Data
-- =====================================================
SELECT *
FROM customer_events
WHERE event_data ->> 'event_type' = 'purchase';
-- =====================================================
-- Nested JSON Query
-- =====================================================
SELECT event_data -> 'metadata' ->> 'browser' AS browser,
COUNT(*)
FROM customer_events
GROUP BY browser
ORDER BY COUNT(*) DESC;
-- =====================================================
-- JSON Path Query
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$.metadata ? (@.browser == "chrome")'
);
-- =====================================================
-- GIN Index (Critical for Performance)
-- =====================================================
CREATE INDEX idx_customer_events_gin
ON customer_events
USING GIN (event_data);
-- =====================================================
-- Expression Index for Frequent Filter
-- =====================================================
CREATE INDEX idx_customer_events_event_type
ON customer_events ((event_data ->> 'event_type'));
-- =====================================================
-- 9️⃣ UPSERT Example
-- =====================================================
INSERT INTO customer_events (customer_id, event_data)
VALUES (1,
'{
"event_type": "purchase",
"amount": 999,
"device": "mobile"
}')
ON CONFLICT (id)
DO UPDATE SET event_data = customer_events.event_data || EXCLUDED.event_data;
-- =====================================================
-- Merge JSON Objects
-- =====================================================
SELECT id,
event_data,
event_data || '{
"processed": true
}'::jsonb AS updated_event
FROM customer_events
LIMIT 20;
-- =====================================================
-- Find Events Where Purchase Amount > 500
-- Demonstrates: Numeric comparison in JSON Path
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$ ? (@.amount > 500)'
);
-- =====================================================
-- Find Mobile Purchases
-- Demonstrates: Multiple conditions with AND
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$ ? (@.event_type == "purchase" && @.device == "mobile")'
);
-- =====================================================
-- Filter Nested JSON Fields
-- Demonstrates: Access nested metadata
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$.metadata ? (@.browser == "chrome")'
);
-- =====================================================
-- Combine Parent + Nested Conditions
-- Demonstrates: Multi-level JSON filtering
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$ ? (@.event_type == "login" && @.metadata.browser == "firefox")'
);
-- =====================================================
-- Extract JSON Values Using JSON Path
-- Demonstrates: jsonb_path_query
-- Returns matching values instead of rows
-- =====================================================
SELECT id,
jsonb_path_query(event_data, '$.metadata.browser') AS browser
FROM customer_events
LIMIT 20;
-- =====================================================
-- Extract Numeric Values
-- Demonstrates: Retrieve purchase amounts
-- =====================================================
SELECT id,
jsonb_path_query(event_data, '$.amount') AS purchase_amount
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$ ? (@.event_type == "purchase")'
)
LIMIT 20;
-- =====================================================
-- Return Full JSON Objects Matching Condition
-- Demonstrates: jsonb_path_query returning structures
-- =====================================================
SELECT id,
jsonb_path_query(event_data, '$ ? (@.device == "mobile")')
FROM customer_events
LIMIT 20;
-- =====================================================
-- Count Chrome Browser Events
-- Demonstrates: JSON Path filtering + aggregation
-- =====================================================
SELECT COUNT(*)
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$.metadata ? (@.browser == "chrome")'
);
-- =====================================================
-- Events With Purchase Amount Between 200 and 400
-- Demonstrates: Range queries
-- =====================================================
SELECT *
FROM customer_events
WHERE jsonb_path_exists(
event_data,
'$ ? (@.amount >= 200 && @.amount <= 400)'
);
-- =====================================================
-- Extract Multiple Fields via JSON Path
-- Demonstrates: jsonb_path_query_first
-- =====================================================
SELECT id,
jsonb_path_query_first(event_data, '$.event_type') AS event_type,
jsonb_path_query_first(event_data, '$.device') AS device
FROM customer_events
LIMIT 20;