Repository navigation
Expand file tree
/
Copy path01_simple_document_store.py
More file actions
522 lines (438 loc) · 19.2 KB
/
Copy path01_simple_document_store.py
File metadata and controls
522 lines (438 loc) · 19.2 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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/env python3
"""
Example 01: Simple Document Store
This example demonstrates the absolute basics of ArcadeDB Python bindings:
- Creating an embedded database (no server needed!)
- Defining document types (schema) with various data types
- CRUD operations (Create, Read, Update, Delete)
- Using transactions safely
- Querying with ArcadeDB SQL (a dialect of SQL)
Perfect for: Configuration storage, logs, simple app data, desktop applications
Think of it as: SQLite but for documents with flexible schema
Record Types Used:
- DOCUMENT TYPE only (simplest data storage, like SQL tables but more flexible)
- Not using VERTEX/EDGE types (those are for graph operations)
Requirements:
- arcadedb
Note: This example creates a database at ./my_test_databases/task_db/
The database files are preserved so you can inspect them after running.
About ArcadeDB SQL:
This example uses ArcadeDB's SQL dialect, which extends standard SQL with:
- Document operations (INSERT/UPDATE with JSON-like syntax)
- Built-in functions like date(), sysDate(), uuid()
- Rich data type support (DATE, DATETIME, DECIMAL, BINARY, etc.)
- Schema-flexible operations alongside typed properties
- No JOINs - relationships use LINKS with dot notation (e.g., user.address.city)
"""
import os
import shutil
import time
import uuid
import arcadedb
print("=" * 70)
print("🎮 ArcadeDB Python - Example 01: Simple Document Store")
print("=" * 70)
print()
# -----------------------------------------------------------------------------
# Step 1: Create Database
# -----------------------------------------------------------------------------
print("Step 1: Creating database...")
print()
step_start = time.time()
# Create database in a local directory so you can inspect the files
# This creates: ./my_test_databases/task_db/
db_dir = "./my_test_databases"
db_path = os.path.join(db_dir, "task_db")
# Clean up any existing database from previous runs
if os.path.exists(db_path):
shutil.rmtree(db_path)
# Clean up log directory from previous runs
if os.path.exists("./log"):
shutil.rmtree("./log")
with arcadedb.create_database(db_path) as db:
print(f" ✅ Database created at: {db_path}")
print(" 💡 Using embedded mode - no server needed!")
print(" 💡 Database files are kept so you can inspect them!")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 2: Create Schema (Document Type with Rich Data Types)
# -----------------------------------------------------------------------------
print("Step 2: Creating schema with various data types...")
print()
step_start = time.time()
# ArcadeDB has 3 record types: Document, Vertex, and Edge
# - Document: Simple data storage (like SQL tables but more flexible)
# - Vertex: Graph nodes for graph operations
# - Edge: Graph connections between vertices
# This example uses DOCUMENT TYPE - the simplest way to store data
print(" 💡 ArcadeDB Record Types:")
print(" • Document: Simple data storage (what we're using)")
print(" • Vertex: Graph nodes for graph operations")
print(" • Edge: Graph connections between vertices")
print()
# While ArcadeDB is schema-flexible, defining types is recommended
# It provides better performance, validation, and indexing
# Schema statements apply immediately (no transaction needed)
db.command("sql", "CREATE DOCUMENT TYPE Task")
# Define properties with various ArcadeDB data types
db.command("sql", "CREATE PROPERTY Task.title STRING") # Text
db.command("sql", "CREATE PROPERTY Task.priority STRING") # Text
db.command("sql", "CREATE PROPERTY Task.completed BOOLEAN") # True/False
db.command("sql", "CREATE PROPERTY Task.tags LIST") # Array of strings
db.command("sql", "CREATE PROPERTY Task.created_date DATE") # Date only
db.command("sql", "CREATE PROPERTY Task.due_datetime DATETIME") # Date + time
db.command("sql", "CREATE PROPERTY Task.estimated_hours FLOAT") # Decimal
db.command("sql", "CREATE PROPERTY Task.priority_score INTEGER") # Integer
db.command("sql", "CREATE PROPERTY Task.cost DECIMAL") # Precision
db.command("sql", "CREATE PROPERTY Task.task_id STRING") # Generated by uuid()
print(" ✅ Created 'Task' document type with rich data types")
print(" 💡 ArcadeDB supports: STRING, BOOLEAN, INTEGER, LONG, FLOAT, DOUBLE,")
print(" DATE, DATETIME, DATETIME_MICROS, DATETIME_NANOS,")
print(" DECIMAL, BINARY, EMBEDDED, LINK, and Arrays")
print(" 💡 Note: UUIDs are stored as STRING type, RIDs use LINK type")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 3: INSERT - Create Documents
# -----------------------------------------------------------------------------
print("Step 3: Inserting documents...")
print()
step_start = time.time()
# IMPORTANT: All write operations should use transactions for ACID guarantees
# (Atomicity, Consistency, Isolation, Durability)
with db.transaction():
# Insert task with full data types
db.command(
"sql",
"""
INSERT INTO Task SET
title = 'Buy groceries',
priority = 'high',
completed = false,
tags = ['shopping', 'urgent'],
created_date = '2024-01-15',
due_datetime = '2024-01-20T18:00:00',
estimated_hours = 2.5,
priority_score = 90,
cost = 150.00,
task_id = ?
""",
str(uuid.uuid4()),
)
# Insert task with some NULL values (optional fields)
db.command(
"sql",
"""
INSERT INTO Task SET
title = 'Write documentation',
priority = 'medium',
completed = false,
tags = ['work', 'writing'],
created_date = '2024-01-16',
due_datetime = null,
estimated_hours = 8.0,
priority_score = 70,
cost = null,
task_id = ?
""",
str(uuid.uuid4()),
)
# Insert completed task with all fields
db.command(
"sql",
"""
INSERT INTO Task SET
title = 'Call dentist',
priority = 'low',
completed = true,
tags = ['personal', 'health'],
created_date = '2024-01-10',
due_datetime = '2024-01-12T10:30:00',
estimated_hours = 0.5,
priority_score = 30,
cost = 0.00,
task_id = ?
""",
str(uuid.uuid4()),
)
# Insert task with many NULL fields (minimal required data)
db.command(
"sql",
"""
INSERT INTO Task SET
title = 'Research ArcadeDB features',
priority = 'medium',
completed = false,
tags = ['work', 'research'],
created_date = '2024-01-17',
due_datetime = null,
estimated_hours = null,
priority_score = 60,
cost = null,
task_id = ?
""",
str(uuid.uuid4()),
)
# Note: Arrays (lists) work naturally - no need for JSON serialization!
# NULL values represent optional/missing data
# task_id comes from Python's uuid4() and is bound as a ? parameter
# rather than pasted into the SQL text
# Documents can contain: strings, numbers, booleans, arrays, nested objects, NULLs
print(" ✅ Inserted 4 tasks (with various data types and NULL values)")
print(" 💡 Transaction committed automatically at end of 'with' block")
print(" 💡 NULL values used for optional fields (due_datetime, cost, etc.)")
print(" 💡 Python uuid4() generates unique task IDs")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 4: QUERY - Read Documents
# -----------------------------------------------------------------------------
print("Step 4: Querying documents...")
print()
step_start = time.time()
# Query all tasks with all properties
print(" 📋 All tasks (with automatic type conversion):")
result = db.query("sql", "SELECT FROM Task ORDER BY priority_score DESC")
# Using the new first() method and automatic type conversion
for record in result:
# Automatic type conversion: no more Java objects!
title = record.get("title") # Now returns Python str directly
priority = record.get("priority") # Python str
completed = record.get("completed") # Python bool
estimated_hours = record.get("estimated_hours") # Python float or None
cost = record.get("cost") # Python Decimal or None
due = record.get("due_datetime") # Python datetime or None
task_id = record.get("task_id") # Python str
status = "✅" if completed else "⏳"
# Handle None values (much cleaner than NULL handling!)
hours_str = f"{estimated_hours}h" if estimated_hours is not None else "N/A"
cost_str = f"${float(cost):.2f}" if cost is not None else "N/A"
due_str = str(due)[:10] if due is not None else "No deadline"
print(f" {status} [{priority:6}] {title}")
print(f" Time: {hours_str}, Cost: {cost_str}, Due: {due_str}")
print(f" UUID: {task_id}")
print()
print(" 💡 NEW: Automatic type conversion!")
print(" • get() now returns native Python types")
print(" • No more Java objects (Integer, BigDecimal, etc.)")
print(" • Decimals are Python Decimal, dates are datetime")
print()
# Query with WHERE clause - find incomplete high priority tasks
print(" 🔥 High priority incomplete tasks:")
result = db.query(
"sql", "SELECT FROM Task WHERE priority = 'high' AND completed = false"
)
# Using new to_list() for efficient bulk conversion
tasks = result.to_list() # Convert all to list of dicts in one operation
for task in tasks:
title = task["title"]
tags = task["tags"] # Automatically converted to Python list!
print(f" • {title}")
print(f" Tags: {', '.join(tags)}")
if not tasks:
print(" (none found)")
else:
print(" 💡 Used to_list() for efficient bulk conversion")
print()
# Query for tasks with NULL values (no deadline)
print(" ⏰ Tasks without deadlines (due_datetime IS NULL):")
result = db.query("sql", "SELECT FROM Task WHERE due_datetime IS NULL")
count = 0
for record in result:
title = str(record.get("title"))
priority = str(record.get("priority"))
print(f" • [{priority}] {title}")
count += 1
if count == 0:
print(" (none found)")
else:
print(f" 💡 Found {count} task(s) with NULL deadline")
print()
# Query for tasks with NULL cost
print(" 💰 Tasks without cost estimate (cost IS NULL):")
result = db.query("sql", "SELECT FROM Task WHERE cost IS NULL")
count = 0
for record in result:
title = str(record.get("title"))
print(f" • {title}")
count += 1
if count == 0:
print(" (none found)")
else:
print(f" 💡 Found {count} task(s) with NULL cost")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 5: UPDATE - Modify Documents (including setting NULL)
# -----------------------------------------------------------------------------
print("Step 5: Updating documents...")
print()
step_start = time.time()
# Mark 'Buy groceries' as completed and add actual cost
with db.transaction():
db.command(
"sql",
"""UPDATE Task SET
completed = true,
cost = 127.50
WHERE title = 'Buy groceries'""",
)
print(" ✅ Marked 'Buy groceries' as completed and set actual cost")
print()
# Update a task to set NULL value (cancel cost estimate)
with db.transaction():
db.command(
"sql",
"""UPDATE Task SET
cost = NULL,
estimated_hours = NULL
WHERE title = 'Call dentist'""",
)
print(" ✅ Cleared cost and time estimates for 'Call dentist' (set to NULL)")
print()
# Verify the updates
print(" 📊 Updated task list (with NULL handling):")
result = db.query("sql", "SELECT FROM Task ORDER BY completed, priority_score DESC")
for record in result:
title = str(record.get("title"))
priority = str(record.get("priority"))
completed = record.get("completed")
cost = record.get("cost")
estimated_hours = record.get("estimated_hours")
status = "✅" if completed else "⏳"
# Show how NULL values appear (convert DECIMAL via string to float)
if cost is not None:
cost_str = f"${float(str(cost)):.2f}"
else:
cost_str = "NULL"
hours_str = f"{estimated_hours}h" if estimated_hours is not None else "NULL"
print(f" {status} [{priority:6}] {title}")
print(f" Cost: {cost_str}, Hours: {hours_str}")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 6: Advanced Queries
# -----------------------------------------------------------------------------
print("Step 6: Running aggregation queries...")
print()
step_start = time.time()
# Count total tasks using new count_type() method
total = db.count_type("Task") # Efficient count without loading data
print(f" 📊 Total tasks: {total}")
print(" 💡 Using new count_type() method (faster than COUNT query)")
print()
# Count by priority
result = db.query(
"sql", "SELECT priority, count(*) as count FROM Task GROUP BY priority"
)
print(" 📊 Tasks by priority:")
for record in result:
priority = str(record.get("priority"))
count = record.get("count")
print(f" • {priority}: {count}")
# Count completed vs incomplete
result = db.query(
"sql", "SELECT completed, count(*) as count FROM Task GROUP BY completed"
)
print(" 📊 Completion status:")
# Using first() and iteration
for record in result:
completed = record.get("completed")
count = record.get("count")
status = "Completed" if completed else "Incomplete"
print(f" • {status}: {count}")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# Demonstrate new ResultSet features
print(" 💡 New ResultSet features demonstrated:")
print(" • to_list() - bulk conversion to list of dicts")
print(" • first() - get first result or None")
print(" • count_type() - efficient record counting")
print(" • Automatic type conversion (no more Java objects!)")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# 💡 ArcadeDB SQL Key Difference: No JOINs
# -----------------------------------------------------------------------------
print("💡 ArcadeDB SQL Key Difference: No JOINs")
print()
print(" ArcadeDB uses LINKS instead of JOINs for relationships.")
print(" Instead of traditional JOIN syntax, use dot notation:")
print()
print(" ❌ Traditional SQL (not supported):")
print(" SELECT * FROM Employee A, City B")
print(" WHERE A.city = B.id AND B.name = 'Rome'")
print()
print(" ✅ ArcadeDB SQL (dot notation):")
print(" SELECT * FROM Employee WHERE city.name = 'Rome'")
print()
print(" This makes queries simpler and more intuitive!")
print()
# -----------------------------------------------------------------------------
# Step 7: DELETE - Remove Documents
# -----------------------------------------------------------------------------
print("Step 7: Deleting documents...")
print()
# Delete completed tasks
with db.transaction():
result = db.command("sql", "DELETE FROM Task WHERE completed = true")
print(" 🗑️ Deleted all completed tasks")
print()
# Verify deletion
result = db.query("sql", "SELECT count(*) as remaining FROM Task")
remaining = list(result)[0].get("remaining")
print(f" 📊 Remaining tasks: {remaining}")
print()
# Show remaining tasks
print(" 📋 Remaining tasks:")
result = db.query("sql", "SELECT FROM Task ORDER BY priority DESC")
for record in result:
title = str(record.get("title"))
priority = str(record.get("priority"))
print(f" ⏳ [{priority:6}] {title}")
print()
# -----------------------------------------------------------------------------
# Step 8: Cleanup
# -----------------------------------------------------------------------------
print("Step 8: Cleanup...")
print()
# Close database connection
print(" ✅ Database closed")
# Note: We're NOT deleting the database directory
# You can inspect the files in ./my_test_databases/task_db/
print(f" 💡 Database files preserved at: {db_path}")
print(" 💡 Inspect the database structure and files!")
print(" 💡 Re-run this script to recreate the database")
print()
print("=" * 70)
print("✅ Example Complete!")
print("=" * 70)
print()
print("📚 What you learned:")
print(" • Creating embedded databases (no server needed)")
print(" • Using context managers for transactions")
print(" • CRUD operations (Document API + SQL)")
print(" • Querying and filtering data")
print(" • Working with flexible document schema")
print()
print("💡 Files created:")
print(" • ./my_test_databases/task_db/ - Database files:")
print(" - configuration.json - Database configuration")
print(" - schema.json - Schema definition (types & properties)")
print(" - Task_0.1.65536.v0.bucket - Data bucket with Task documents")
print(" - dictionary.0.327680.v0.dict - String compression dictionary")
print(" - statistics.json - Database statistics")
print(
" • ARCADEDB_LOG_DIR (default: a per-user state directory) - ArcadeDB and JVM log files"
)
print()
print("💡 Next steps:")
print(" • See docs/examples/ for detailed explanations")
print(" • See docs/guide/operations.md for file structure and logging")
print()
print("🔗 API Documentation:")
print(" • Database: docs/api/database.md")
print(" • Transactions: docs/api/transactions.md")
print(" • Results: docs/api/results.md")
print()