Repository navigation
Expand file tree
/
Copy path04_csv_import_documents.py
More file actions
2469 lines (2163 loc) Β· 87.9 KB
/
Copy path04_csv_import_documents.py
File metadata and controls
2469 lines (2163 loc) Β· 87.9 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Example 04: CSV Import - Documents with Bulk Insert Ingest
This example demonstrates importing CSV data into ArcadeDB DOCUMENTS
using bulk INSERT statements with explicit schema mapping.
We use the MovieLens dataset with four CSV files:
- movies.csv: Movie information (9,743 movies)
- ratings.csv: User ratings (100,837 ratings)
- links.csv: External movie IDs (9,742 links)
- tags.csv: User-generated tags (3,683 tags)
Key Concepts:
- Bulk INSERT ingest using Python CSV parsing
- Explicit schema mapping for document types
- Batch processing with --batch-size (transaction size for the CSV ingest)
- Read-your-writes disabled during ingest, then re-enabled
- Creating indexes AFTER import for performance
- **Full-text search** with Lucene for text fields
- Query performance comparison with/without indexes
- NULL value handling
Schema Strategy:
- Integer-like values β LONG
- Decimal values β DOUBLE
- Text values β STRING
- Empty cells β NULL (proper SQL NULL handling)
Supported ArcadeDB Types:
Numeric:
- BYTE: 8-bit integer (-128 to 127)
- SHORT: 16-bit integer (-32,768 to 32,767)
- INTEGER: 32-bit integer (-2.1B to 2.1B)
- LONG: 64-bit integer (large numbers) β Java's default for integers
- FLOAT: 32-bit decimal (~7 digits precision)
- DOUBLE: 64-bit decimal (~15 digits precision) β Java's default for decimals
- DECIMAL: Arbitrary precision (exact, for money)
Other:
- STRING, BOOLEAN, DATE, DATETIME, BINARY, EMBEDDED, LIST
Requirements:
- arcadedb
- MovieLens dataset (downloaded via download_data.py)
- Sufficient JVM heap memory (8GB recommended for large dataset)
Usage:
1. Run with default (large) dataset:
python 04_csv_import_documents.py
2. Run with small dataset:
python 04_csv_import_documents.py --dataset movielens-small
3. Run with custom batch size:
python 04_csv_import_documents.py --batch-size 10000
4. Run with custom JVM heap and batch size:
python 04_csv_import_documents.py --dataset movielens-large --batch-size 10000 --heap-size 8g
The script will automatically download the dataset if it doesn't exist.
Memory Requirements:
- Small dataset (~100K ratings): 4GB heap (default) is sufficient
- Large dataset (~33M ratings): 4GB heap (default) should work, 8GB for safety
- Very large datasets (100M+ records): Use --heap-size 8g or higher
Dataset Options:
- movielens-small: ~1 MB, ~100K ratings, 9K movies, 600 users
- movielens-large: ~265 MB, ~33M ratings, 86K movies, 280K users
Note: This example creates a database at ./my_test_databases/movielens_db/
The database files are preserved so you can inspect them after running.
"""
import argparse
import csv
import json
import os
import shutil
import statistics
import subprocess
import sys
import time
from pathlib import Path
import arcadedb
# Define test queries used for validation
# NOTE: ORDER BY clauses ensure consistent results across runs (important for validation)
TEST_QUERIES = [
("Find movie by ID", "SELECT FROM Movie WHERE movieId = 500"),
(
"Find user's ratings",
"SELECT FROM Rating WHERE userId = 414 ORDER BY movieId, rating LIMIT 10",
),
(
"Find movie ratings",
"SELECT FROM Rating WHERE movieId = 500 ORDER BY userId, rating LIMIT 10",
),
(
"Count user's ratings",
"SELECT count(*) as count FROM Rating WHERE userId = 414",
),
(
"Find movies by genre (LIKE with LIMIT)",
"SELECT FROM Movie WHERE genres LIKE '%Action%' ORDER BY movieId LIMIT 10",
),
(
"Count ALL Action movies (LIKE, no LIMIT)",
"SELECT count(*) as count FROM Movie WHERE genres LIKE '%Action%'",
),
]
# Expected baseline results for validation
EXPECTED_RESULTS = {
"movielens-small": [
{
"name": "Find movie by ID",
"count": 1,
"sample": [
{
"movieId": 500,
"title": "Mrs. Doubtfire (1993)",
"genres": "Comedy|Drama",
"@props": "movieId:3,title:7,genres:7",
}
],
},
{
"name": "Find user's ratings",
"count": 10,
"sample": [
{
"userId": 414,
"movieId": 1,
"rating": 4.0,
"timestamp": 961438127,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 2,
"rating": 3.0,
"timestamp": 961594981,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 3,
"rating": 4.0,
"timestamp": 961439278,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 5,
"rating": 2.0,
"timestamp": 961437647,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 6,
"rating": 3.0,
"timestamp": 961515642,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
],
},
{
"name": "Find movie ratings",
"count": 10,
"sample": [
{
"userId": 1,
"movieId": 500,
"rating": 3.0,
"timestamp": 964981208,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 6,
"movieId": 500,
"rating": 5.0,
"timestamp": 845553354,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 8,
"movieId": 500,
"rating": 2.0,
"timestamp": 839463624,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 18,
"movieId": 500,
"rating": 3.5,
"timestamp": 1455618095,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 19,
"movieId": 500,
"rating": 2.0,
"timestamp": 965706636,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
],
},
{"name": "Count user's ratings", "count": 1, "sample": [{"count": 2698}]},
{
"name": "Find movies by genre (LIKE with LIMIT)",
"count": 10,
"sample": [
{
"movieId": 6,
"title": "Heat (1995)",
"genres": "Action|Crime|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 9,
"title": "Sudden Death (1995)",
"genres": "Action",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 10,
"title": "GoldenEye (1995)",
"genres": "Action|Adventure|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 15,
"title": "Cutthroat Island (1995)",
"genres": "Action|Adventure|Romance",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 20,
"title": "Money Train (1995)",
"genres": "Action|Comedy|Crime|Drama|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
],
},
{
"name": "Count ALL Action movies (LIKE, no LIMIT)",
"count": 1,
"sample": [{"count": 1796}],
},
],
"movielens-large": [
{
"name": "Find movie by ID",
"count": 1,
"sample": [
{
"movieId": 500,
"title": "Mrs. Doubtfire (1993)",
"genres": "Comedy|Drama",
"@props": "movieId:3,title:7,genres:7",
}
],
},
{
"name": "Find user's ratings",
"count": 10,
"sample": [
{
"userId": 414,
"movieId": 1,
"rating": 5.0,
"timestamp": 1603897313,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 34,
"rating": 3.5,
"timestamp": 1603897729,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 47,
"rating": 5.0,
"timestamp": None,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 50,
"rating": 4.0,
"timestamp": 1603896782,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 414,
"movieId": 260,
"rating": 4.0,
"timestamp": 1603897681,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
],
},
{
"name": "Find movie ratings",
"count": 10,
"sample": [
{
"userId": 2,
"movieId": 500,
"rating": 4.0,
"timestamp": 835816548,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 7,
"movieId": 500,
"rating": 4.0,
"timestamp": 974520592,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 9,
"movieId": 500,
"rating": 4.0,
"timestamp": 835947950,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 14,
"movieId": 500,
"rating": 2.0,
"timestamp": 1311601190,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 21,
"movieId": 500,
"rating": 3.0,
"timestamp": 1172734846,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
],
"sample_indexed": [
{
"userId": 198520,
"movieId": 500,
"rating": 3.0,
"timestamp": 841556879,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 198564,
"movieId": 500,
"rating": 4.0,
"timestamp": 834049208,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 198901,
"movieId": 500,
"rating": 3.0,
"timestamp": 876049592,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 199071,
"movieId": 500,
"rating": 3.5,
"timestamp": 1487972691,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
{
"userId": 199347,
"movieId": 500,
"rating": 5.0,
"timestamp": 841305883,
"@props": "userId:3,movieId:3,rating:5,timestamp:3",
},
],
},
{"name": "Count user's ratings", "count": 1, "sample": [{"count": 169}]},
{
"name": "Find movies by genre (LIKE with LIMIT)",
"count": 10,
"sample": [
{
"movieId": 6,
"title": "Heat (1995)",
"genres": "Action|Crime|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 9,
"title": "Sudden Death (1995)",
"genres": "Action",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 10,
"title": "GoldenEye (1995)",
"genres": "Action|Adventure|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 15,
"title": "Cutthroat Island (1995)",
"genres": "Action|Adventure|Romance",
"@props": "movieId:3,title:7,genres:7",
},
{
"movieId": 20,
"title": "Money Train (1995)",
"genres": "Action|Comedy|Crime|Drama|Thriller",
"@props": "movieId:3,title:7,genres:7",
},
],
},
{
"name": "Count ALL Action movies (LIKE, no LIMIT)",
"count": 1,
"sample": [{"count": 9386}],
},
],
}
# =============================================================================
# Helper Functions: Index Management
# =============================================================================
def serialize_query_results(results):
"""
Convert query results to JSON-serializable format.
Args:
results: List of result dicts from run_validation_queries()
Returns:
List of dicts with serializable data
"""
serialized = []
for result in results:
# Extract sample data if available
sample_data = []
if result.get("sample"):
for record in result["sample"]:
record_dict = {}
# Get all properties from the record
record_json = json.loads(record.to_json())
for key, value in record_json.items():
if key not in ["@rid", "@cat", "@type"]:
record_dict[key] = value
sample_data.append(record_dict)
serialized.append(
{
"name": result["name"],
"count": result["count"],
"sample": sample_data[:5], # Save first 5 results
}
)
return serialized
def save_query_results(results, dataset_size, db_path):
"""
Save query results to a JSON file for later comparison.
Args:
results: List of result dicts from run_validation_queries()
dataset_size: "small" or "large"
db_path: Path to the database directory where results should be saved
Returns:
Path to saved file
"""
# Save results in the database directory
db_dir = Path(db_path)
db_dir.mkdir(parents=True, exist_ok=True)
results_file = db_dir / f"query_results_{dataset_size}.json"
serialized_results = serialize_query_results(results)
with open(results_file, "w") as f:
json.dump(serialized_results, f, indent=2)
return results_file
def compare_query_results(current_results, saved_results, verbose=True):
"""
Compare current query results against saved baseline.
Args:
current_results: List of result dicts from run_validation_queries()
saved_results: List of saved result dicts
verbose: If True, print comparison details
Returns:
bool: True if all results match, False otherwise
"""
if verbose:
print(" π Comparing against saved baseline results...")
print()
all_match = True
serialized_current = serialize_query_results(current_results)
for i, (current, saved) in enumerate(zip(serialized_current, saved_results)):
query_name = current["name"]
# Compare counts
if current["count"] != saved["count"]:
if verbose:
print(
f" β {query_name}: Count mismatch! "
f"Current: {current['count']}, Saved: {saved['count']}"
)
all_match = False
continue
# Compare sample data
current_sample = current["sample"]
saved_sample = saved["sample"]
# Compare samples as JSON strings (normalized, ignoring key order)
def normalize_record(rec):
"""Sort keys and exclude @props metadata for comparison."""
# Exclude @props as it's internal metadata that may change order
return {k: rec[k] for k in sorted(rec.keys()) if k != "@props"}
current_normalized = [normalize_record(r) for r in current_sample]
saved_normalized = [normalize_record(r) for r in saved_sample]
if current_normalized != saved_normalized:
# Check for alternative sample (e.g. indexed) if available
# This handles cases where indexes change the sort order (e.g. String vs Int sorting)
match_found = False
if "sample_indexed" in saved:
saved_sample_indexed = saved["sample_indexed"]
saved_normalized_indexed = [
normalize_record(r) for r in saved_sample_indexed
]
if current_normalized == saved_normalized_indexed:
if verbose:
print(
f" β
{query_name}: {current['count']} results (matches indexed baseline)"
)
match_found = True
if not match_found:
if verbose:
print(
f" β οΈ {query_name}: Sample data differs "
f"(count matches: {current['count']})"
)
# Show first difference
for j, (curr_rec, saved_rec) in enumerate(
zip(current_normalized, saved_normalized)
):
if curr_rec != saved_rec:
print(f" First difference at record {j}:")
print(f" Current: {curr_rec}")
print(f" Saved: {saved_rec}")
break
all_match = False
else:
if verbose:
print(f" β
{query_name}: {current['count']} results (matches)")
return all_match
# =============================================================================
# Helper Functions: Index Management
# =============================================================================
def create_indexes(db, indexes, verbose=True):
"""
Create indexes with retry logic for compaction conflicts.
Args:
db: Database instance
indexes: List of (table, column, uniqueness) tuples
uniqueness can be: "UNIQUE", "UNIQUE_HASH", "NOTUNIQUE",
"NOTUNIQUE_HASH", "FULL_TEXT"
verbose: If True, print progress messages
Returns:
tuple: (success_count, failed_indexes)
success_count: Number of indexes created successfully
failed_indexes: List of (table, column, error) tuples that failed
"""
if verbose:
print(
f"\n π Creating {len(indexes)} indexes "
f"with retry on compaction conflicts:"
)
success_count = 0
failed_indexes = []
for idx, (table, column, uniqueness) in enumerate(indexes, 1):
created = False
retry_delay = 300 # Wait 300 seconds (5 minutes) between retries
max_retries = 200 # Try for up to 200 attempts (= 1000 minutes max per index)
for attempt in range(1, max_retries + 1):
try:
# Convert uniqueness string to SQL index creation
if uniqueness == "UNIQUE":
db.command("sql", f"CREATE INDEX ON {table} ({column}) UNIQUE")
elif uniqueness == "UNIQUE_HASH":
db.command("sql", f"CREATE INDEX ON {table} ({column}) UNIQUE_HASH")
elif uniqueness == "FULL_TEXT":
db.command("sql", f"CREATE INDEX ON {table} ({column}) FULL_TEXT")
elif uniqueness == "NOTUNIQUE_HASH":
db.command(
"sql", f"CREATE INDEX ON {table} ({column}) NOTUNIQUE_HASH"
)
else: # NOTUNIQUE
db.command("sql", f"CREATE INDEX ON {table} ({column}) NOTUNIQUE")
if verbose:
print(
f" β
[{idx}/{len(indexes)}] "
f"Created index on {table}({column}) {uniqueness}"
)
created = True
success_count += 1
break
except Exception as e: # noqa: BLE001
error_msg = str(e)
# Check if retryable (compaction or index conflicts)
is_compaction_error = (
"NeedRetryException" in error_msg
and "asynchronous tasks" in error_msg
)
is_index_error = (
"IndexException" in error_msg
and "Error on creating index" in error_msg
)
if is_compaction_error or is_index_error:
if attempt < max_retries:
elapsed = attempt * retry_delay
reason = (
"compaction running"
if is_compaction_error
else "index conflict"
)
if verbose:
print(
f" β³ [{idx}/{len(indexes)}] "
f"Waiting for {reason} "
f"(attempt {attempt}/{max_retries}, "
f"{elapsed}s elapsed)..."
)
time.sleep(retry_delay)
else:
if verbose:
print(
f" β [{idx}/{len(indexes)}] "
f"Failed to create index on "
f"{table}({column}) "
f"after {max_retries} retries"
)
failed_indexes.append((table, column, error_msg))
break
else:
# Non-retryable error
if verbose:
print(
f" β [{idx}/{len(indexes)}] Failed to create index on "
f"{table}({column}): {error_msg}"
)
failed_indexes.append((table, column, error_msg))
break
if not created and verbose:
print(f" β οΈ Skipping index {table}({column})")
return success_count, failed_indexes
def drop_all_indexes(db, verbose=True):
"""
Drop all non-RID indexes from the database.
Args:
db: Database instance
verbose: If True, print progress messages
Returns:
int: Number of indexes dropped
"""
if verbose:
print("\n ποΈ Dropping all indexes...")
dropped_count = 0
try:
# Get all indexes - use the correct query format
result = db.query(
"sql", "SELECT name, typeName, properties FROM schema:indexes"
)
indexes = list(result)
if verbose:
print(f" π Found {len(indexes)} indexes")
for index_record in indexes:
index_name = index_record.get("name")
# Try to drop all indexes
# Note: Some system indexes cannot be dropped and will fail gracefully
try:
# Drop the index
db.command("sql", f"DROP INDEX `{index_name}`")
dropped_count += 1
if verbose:
print(f" β
Dropped index: {index_name}")
except Exception as e: # noqa: BLE001
if verbose:
# Only show if it's not a "cannot drop" error
error_msg = str(e)
if "cannot" not in error_msg.lower():
print(f" β οΈ Could not drop {index_name}: {e}")
if verbose:
print(f" β
Dropped {dropped_count} indexes")
except Exception as e: # noqa: BLE001
if verbose:
print(f" β οΈ Error querying indexes: {e}")
return dropped_count
def wait_for_compaction(db, max_wait_seconds=600, verbose=True):
"""
Wait for background compaction to complete before performing operations.
Args:
db: Database instance
max_wait_seconds: Maximum time to wait (default 10 minutes)
verbose: If True, print progress messages
Returns:
bool: True if compaction completed, False if timeout
"""
if verbose:
print(" β³ Waiting for background compaction to complete...")
retry_interval = 5 # Check every 5 seconds
wait_start = time.time()
while (time.time() - wait_start) < max_wait_seconds:
try:
# Read-only probe; no transaction required
db.query("sql", "SELECT count(*) FROM Movie LIMIT 1").first()
if verbose:
print(" β
Background compaction complete")
return True
except Exception as e: # noqa: BLE001
if "NeedRetryException" in str(e) or "asynchronous tasks" in str(e):
elapsed = time.time() - wait_start
if verbose:
print(f" β³ Still compacting... ({elapsed:.0f}s elapsed)")
time.sleep(retry_interval)
else:
if verbose:
print(f" β οΈ Unexpected error while waiting: {e}")
return False
if verbose:
print(
f" β οΈ Compaction still running after {max_wait_seconds}s, "
f"proceeding anyway"
)
return False
def run_validation_queries(db, queries=None, num_runs=1, verbose=True):
"""
Run validation queries against a database.
Args:
db: Database instance to query
queries: List of (name, query) tuples. If None, uses TEST_QUERIES
num_runs: Number of times to run each query (for performance testing)
verbose: If True, print detailed statistics
Returns:
List of dicts with query results and statistics
"""
if queries is None:
queries = TEST_QUERIES
results = []
for query_name, query in queries:
run_times = []
result_count = 0
sample_result = None
for i in range(num_runs):
query_start = time.time()
result = list(db.query("sql", query))
query_time = time.time() - query_start
run_times.append(query_time)
result_count = len(result)
# Capture first result for validation
if i == 0:
sample_result = result
# Calculate statistics
avg_time = statistics.mean(run_times)
std_time = statistics.stdev(run_times) if len(run_times) > 1 else 0
min_time = min(run_times)
max_time = max(run_times)
results.append(
{
"name": query_name,
"runs": run_times,
"avg": avg_time,
"std": std_time,
"min": min_time,
"max": max_time,
"count": result_count,
"sample": sample_result,
}
)
if verbose:
print(f" π {query_name}:")
if num_runs > 1:
print(f" Average: {avg_time:.3f}s Β± {std_time:.3f}s")
print(f" Range: [{min_time:.3f}s - {max_time:.3f}s]")
else:
print(f" Time: {avg_time:.3f}s")
print(f" Results: {result_count}")
print()
return results
def download_dataset(dataset_name):
"""Download the dataset using download_data.py script.
Args:
dataset_name: Dataset name (e.g., "movielens-small", "movielens-large")
"""
download_script = Path(__file__).parent / "download_data.py"
if not download_script.exists():
print(f"β Download script not found: {download_script}")
print(" Please ensure download_data.py is in the same directory.")
sys.exit(1)
print(f"π₯ Downloading {dataset_name} dataset...")
print(f" Running: python {download_script} {dataset_name}")
print()
try:
subprocess.run(
[sys.executable, str(download_script), dataset_name],
check=True,
capture_output=False,
)
print()
print("β
Dataset downloaded successfully!")
print()
except subprocess.CalledProcessError as e:
print(f"β Failed to download dataset: {e}")
sys.exit(1)
def check_dataset_exists(data_dir):
"""Check if all required CSV files exist in the dataset directory."""
required_files = ["movies.csv", "ratings.csv", "links.csv", "tags.csv"]
if not data_dir.exists():
return False
for csv_file in required_files:
if not (data_dir / csv_file).exists():
return False
return True
# Parse command-line arguments
parser = argparse.ArgumentParser(
description="Example 04: Import MovieLens dataset into ArcadeDB",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python 04_csv_import_documents.py # Use large dataset (default)
python 04_csv_import_documents.py --dataset movielens-small # Use small dataset
python 04_csv_import_documents.py --dataset movielens-large # Use large dataset
python 04_csv_import_documents.py --batch-size 10000 # Use larger batch size
python 04_csv_import_documents.py --export # Export database after import
python 04_csv_import_documents.py --export --export-path my_backup.jsonl.tgz
Dataset sizes:
large - movielens-large (~33M ratings, ~86K movies, ~265 MB) - DEFAULT
small - movielens-small (~100K ratings, ~9K movies, ~1 MB)
Parallel (--parallel):
Passed as `parallel` to the IMPORT DATABASE of the --export round trip, and
used nowhere else. The CSV ingest runs single-threaded in batched
transactions, and the engine's JSONL importer does not read `parallel`.
Default: not passed.
Batch size (--batch-size):
Default: 5000 records per commit. Sets the transaction size for the CSV
ingest. It is also passed as commitEvery to the round-trip IMPORT DATABASE,
which the JSONL importer does not read.
Larger batches = faster imports, more memory usage
Smaller batches = slower imports, less memory usage
Export:
--export: Enable database export to JSONL format after import
--export-path: Export filename (default: {db_name}.jsonl.tgz in exports/ dir)
Use exports to create reproducible benchmark databases or backups
The script will automatically download the dataset if it doesn't exist.
""",
)
parser.add_argument(
"--dataset",
choices=["movielens-small", "movielens-large"],
default="movielens-large",
help="Dataset size to use (default: movielens-large)",
)
parser.add_argument(
"--parallel",
type=int,
default=None,
help=(
"Passed as `parallel` to the IMPORT DATABASE of the --export round trip "
"and used nowhere else: the CSV ingest is single-threaded, and the JSONL "
"importer does not read it (default: not passed)"
),
)
parser.add_argument(
"--batch-size",
type=int,
default=5000,
help="Number of records to commit per batch (default: 5000)",
)
parser.add_argument(
"--heap-size",
type=str,
default=None,
help="Set JVM max heap size (e.g. 8g, 4096m). Default: 50 percent of the RAM the JVM sees.",
)
parser.add_argument(
"--db-name",
type=str,
default=None,
help="Database name (default: based on dataset name, e.g., movielens_small_db)",
)
parser.add_argument(
"--export",
action="store_true",
help="Export database to JSONL after import (for reproducibility)",
)
parser.add_argument(
"--export-path",
type=str,
default=None,
help="Export filename (default: {db_name}.jsonl.tgz in exports/ directory)",
)
args = parser.parse_args()
# Start script timer
script_start_time = time.time()
print("=" * 70)
print("π¬ ArcadeDB Python - Example 04: CSV Import - Documents")
print("=" * 70)
print()
print(f"π Dataset: {args.dataset}")
if args.parallel:
# The CSV ingest below is single-threaded; --parallel only reaches the
# WITH clause of the --export round trip's IMPORT DATABASE.
print(
f"π§ --parallel {args.parallel}: passed to the round-trip "
"IMPORT DATABASE (only with --export)"