-
Notifications
You must be signed in to change notification settings - Fork 0
/
object_examples.py
308 lines (272 loc) · 9.91 KB
/
object_examples.py
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# ruff: noqa: W291 Trailing whitespace
# Example script showing different types of interactions with
# objects in CrateDB. This has no hardware dependencies so should
# run in any MicroPython environment. You will need to edit the
# code below to use your CrateDB credentials.
import cratedb
# CrateDB Docker / local network, no SSL.
crate = cratedb.CrateDB(host="localhost", use_ssl=False)
# CrateDB Cloud, using SSL.
"""
crate = cratedb.CrateDB(
host="testdrive.cratedb.net",
user="username",
password="password"
)
"""
try:
print("Drop any previous table.")
crate.execute("DROP TABLE IF EXISTS driver_object_test", return_response=False)
# Create a table, using a dynamic object column.
print("Create table.")
response = crate.execute(
"CREATE TABLE driver_object_test (id TEXT PRIMARY KEY, data OBJECT(DYNAMIC))"
)
# response:
# {'rows': [[]], 'rowcount': 1, 'cols': [], 'duration': 270.4579}
print(response)
# Insert an object with arbitrary complexity.
print("INSERT a row containing an object.")
example_obj = {
"sensor_readings": {"temp": 23.3, "humidity": 61.2},
"metadata": {
"software_version": "1.19",
"battery_percentage": 57,
"uptime": 2851200,
},
}
response = crate.execute(
"INSERT INTO driver_object_test (id, data) VALUES (?, ?)", ["2cae54", example_obj]
)
# response:
# {'rows': [[]], 'rowcount': 1, 'cols': [], 'duration': 334.37607}
print(response)
# Select query returning the entire object.
print("SELECT the whole object.")
response = crate.execute(
"SELECT data FROM driver_object_test WHERE id = ?", ["2cae54"]
)
# response:
# {'rows': [
# [{
# 'metadata': {'software_version': '1.19', 'uptime': 2851200,
# 'battery_percentage': 57},
# 'sensor_readings': {'humidity': 61.2, 'temp': 23.3}}
# ]
# ], 'rowcount': 1, 'cols': ['data'], 'duration': 21.946375
# }
print(response)
# Select query returning some fields from the object.
print("SELECT some parts of the object but not all.")
response = crate.execute(
"""SELECT
id,
data['metadata']['uptime'] AS uptime,
data['sensor_readings'] AS sensor_readings
FROM driver_object_test
WHERE id = ?""",
["2cae54"],
)
# response:
# {'rows': [
# [2851200, {'humidity': 61.2, 'temp': 23.3}]
# ],
# 'rowcount': 1, 'cols': ['uptime', 'sensor_readings'], 'duration': 4.047666
# }
print(response)
# Bulk insert additional objects.
response = crate.execute(
"INSERT INTO driver_object_test (id, data) VALUES (?, ?)",
[
[
"2cae56",
{
"sensor_readings": {"temp": 21.8, "humidity": 57.9},
"metadata": {
"software_version": "1.19",
"battery_percentage": 43,
"uptime": 2851643,
},
},
],
[
"1d452b",
{
"sensor_readings": {"temp": 11.4, "humidity": 43.9},
"metadata": {
"software_version": "1.20",
"battery_percentage": 17,
"uptime": 853436,
},
},
],
[
"4e000f",
{
"sensor_readings": {"temp": 26.8, "humidity": 78.9},
"metadata": {
"software_version": "1.19",
"battery_percentage": 84,
"uptime": 1468356,
},
},
],
],
)
# response:
# {'results': [
# {'rowcount': 1},
# {'rowcount': 1},
# {'rowcount': 1}
# ], 'cols': [], 'duration': 4.426417
# }
print(response)
# Tells the database to refresh the table. This is here to make sure that the
# subsequent SELECT has the data from the INSERT above. This is not needed in
# real application code.
# See https://cratedb.com/docs/crate/reference/en/latest/sql/statements/refresh.html
# for details.
crate.execute("REFRESH TABLE driver_object_test", return_response=False)
# SELECT example that filters by an object property in the WHERE clause.
print("SELECT and filter by an object property in the WHERE clause.")
response = crate.execute(
"""
SELECT id, data['sensor_readings'] AS sensor_readings FROM driver_object_test
WHERE data['metadata']['software_version'] = '1.19'
"""
)
# response:
# { 'rows': [
# ['4e000f', {'humidity': 78.90000000000001, 'temp': 26.8}],
# ['2cae54', {'humidity': 61.2, 'temp': 23.3}],
# ['2cae56', {'humidity': 57.9, 'temp': 21.8}]
# ], 'rowcount': 3, 'cols': ['id', 'sensor_readings'], 'duration': 13.790875}
print(response)
# Add some sample data about different countries in South America, their
# borders and currency exchange rates.
print("Add country data for Colombia and Brazil.")
response = crate.execute(
"""
INSERT INTO driver_object_test (id, data) VALUES (?, ?)
""",
[
[
"co",
{
"name": "Colombia",
"borders": ["Brazil", "Peru", "Panama", "Ecuador", "Venezuela"],
"currency": {"code": "COP", "name": "Colobian Peso"},
"rates": [
{"code": "USD", "rate": "0.000235"},
{"code": "EUR", "rate": "0.000216"},
{"code": "JPY", "rate": "0.035154"},
],
},
],
[
"br",
{
"name": "Brazil",
"borders": [
"Argentina",
"Bolivia",
"Colombia",
"French Guiana",
"Guyana",
"Paraguay",
"Suriname",
"Uruguay",
"Venezuela",
],
"currency": {"code": "BRL", "name": "Brazilian Real"},
"rates": [
{"code": "USD", "rate": "0.176620"},
{"code": "EUR", "rate": "0.162409"},
{"code": "JPY", "rate": "26.432108"},
],
},
],
],
)
# response:
# {'results': [{'rowcount': 1}, {'rowcount': 1}], 'cols': [], 'duration': 46.436874}
print(response)
# Some examples showing how to access data inside arrays.
# See also https://cratedb.com/docs/crate/reference/en/latest/general/builtins/scalar-functions.html#array-functions
# Simple array... which countries does Colombia share a border with?
print("Arrays... countries sharing a border with Colombia.")
response = crate.execute(
"""
SELECT data['borders'] as shares_border_with
FROM driver_object_test WHERE id = 'co'
"""
)
# response:
# {'rows': [[['Brazil', 'Peru', 'Panama', 'Ecuador', 'Venezuela']]],
# 'rowcount': 1, 'cols': ['shares_border_with'], 'duration': 50.105873}
print(response)
# How many countries does Brazil share a border with?
print("How many entries are in an array?")
response = crate.execute(
# 1 here is the array dimension to get the length of, as arrays can be nested.
"""
SELECT array_length(data['borders'], 1) AS how_many
FROM driver_object_test WHERE id = 'br'
"""
)
# response:
# {'rows': [[9]], 'rowcount': 1, 'cols': ['how_many'], 'duration': 1.397291}
print(response)
# What are the 2nd, 3rd and 4th countries in Brazil's borders array?
# Arrays are 1-indexed.
print("Array slicing.")
response = crate.execute(
"""
SELECT array_slice(data['borders'], 2, 4) AS slice
FROM driver_object_test WHERE id = 'br'
"""
)
# response:
# {'rows': [[['Bolivia', 'Colombia', 'French Guiana']]], 'rowcount': 1,
# 'cols': ['slice'], 'duration': 1.517417}
print(response)
# Example queries for arrays containing objects.
# Retrieve the currency code for the 2nd currency rate object in the rates array.
# Remember, arrays are 1 indexed.
print("Mixing objects and arrays...")
response = crate.execute(
"""
SELECT data['rates'][2]['code']
FROM driver_object_test WHERE id='co'
"""
)
# response:
# {'rows': [['EUR']], 'rowcount': 1,
# 'cols': ["data[2]['rates']['code']"], 'duration': 0.553541}
print(response)
# Array comparisons.
# https://cratedb.com/docs/crate/reference/en/latest/general/builtins/array-comparisons.html#sql-array-comparisons
# Which countries share a border with Paraguay?
print("Element in array: Who shares a border with Paraguay?")
response = crate.execute(
"""
SELECT data['name'] AS name, 'Paraguay' IN (data['borders']) AS borders_paraguay
FROM driver_object_test WHERE id IN ('br', 'co')
"""
)
# response:
# {'rows': [['Colombia', False], ['Brazil', True]], 'rowcount': 2,
# 'cols': ['name', 'borders_paraguay'], 'duration': 0.574833}
print(response)
# Drop the table.
print("Drop table...")
response = crate.execute("DROP TABLE driver_object_test")
# response:
# {'rows': [[]], 'rowcount': 1, 'cols': [], 'duration': 67.91708}
print(response)
except cratedb.NetworkError as e:
print("Caught NetworkError:")
print(e)
except cratedb.CrateDBError as c:
print("Caught CrateDBError:")
print(c)