Repository navigation
Expand file tree
/
Copy path05_csv_import_graph.py
More file actions
2711 lines (2401 loc) · 101 KB
/
Copy path05_csv_import_graph.py
File metadata and controls
2711 lines (2401 loc) · 101 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 05: Graph Creation Benchmark - Clean Architecture
This benchmark compares graph creation strategies with multiple options:
- Method: Java API vs SQL
- Batch: GraphBatch (buffered) vs Synchronous transactions (sequential)
- Indexes: With indexes vs Without indexes
Architecture:
=============
- Shared data loading functions (properly paginated)
- Shared vertex creation logic
- Shared edge creation logic
- Method-specific executors (Java API vs SQL)
- Bulk vertex creation:
* Java mode: GraphBatch, one boundary crossing per batch.
* SQL mode: Synchronous transactions for bulk vertex creation.
- Index-aware implementations
Bulk vertex path:
=================
**Java mode + batch (default for `--method java`):**
- Uses GraphBatch: rows cross the boundary once per batch and every row lands
- Command: `--method java`
- `--parallel` selects GraphBatch's parallel flush rather than an async
executor parallel level
**Java mode + `--no-async`:**
- Synchronous transactions, one INSERT per row
- Slower, same resulting graph
**SQL Mode (ALWAYS SYNCHRONOUS FOR VERTICES):**
- Direct SQL commands via transactions
- Sequential processing (one operation at a time)
- Command: `--method sql`
- The `--no-async` flag has no effect on SQL (always synchronous)
Note: vertex creation here used to submit one INSERT per row through
`async_executor().command(...)`. That path silently dropped records above
parallel level 1 before 26.10.1 (ArcadeData/arcadedb#7615, fixed in #7625), so
it is gone from this example.
GraphBatch drives the same executor for its edge flush and is measured exact.
Proper Database-Level Streaming:
=================================
ALL queries use LIMIT-based pagination to avoid loading entire result sets:
- Link data: Paginated with @rid > {last_rid} LIMIT {batch_size}
- Movies: Paginated with @rid > {last_rid} LIMIT {batch_size}
- Ratings: Paginated with @rid > {last_rid} LIMIT {batch_size}
- Tags: Paginated with @rid > {last_rid} LIMIT {batch_size}
Exception: User vertices group the ratings by user, `SELECT userId FROM Rating GROUP BY userId`
(difficult to paginate efficiently; GROUP BY rather than SELECT DISTINCT, because the
ORDER BY keeps a DISTINCT off the parallel path, ArcadeData/arcadedb#8799)
Dataset Sources:
----------------
Two options for loading source data:
**Option 1: Document Database (default, --source-db)**
Reads from Document DB (created by 04_csv_import_documents.py):
- Rating → RATED edges (User → Movie)
- Tag → TAGGED edges (User → Movie)
- Movie → Movie vertices
- Link → merged into Movie vertices (imdbId, tmdbId)
**Option 2: Imported JSONL (--import-jsonl)**
Imports pre-exported JSONL file and reads from imported database:
- Faster initial setup (no CSV import needed)
- Good for reproducible benchmarks
- Measures import time separately
- Example: --import-jsonl ./exports/movielens_small_db.jsonl.tgz
Rows the graph deliberately does not carry:
===========================================
download_data.py injects NULLs into the MovieLens CSVs on purpose (seeded, so
the same rows every time): 3% of ratings.csv rows get an empty timestamp, 1%
get an empty rating, 5% of tags.csv rows get an empty tag and 2% an empty
timestamp. Example 04 imports all of them, empty cell -> SQL NULL, because
NULL handling is what that example is about.
This example builds edges whose timestamp is a declared LONG, so it selects
only source rows that have one:
- RATED: WHERE timestamp IS NOT NULL -> 97,823 of 100,836 Rating docs
- TAGGED: WHERE timestamp IS NOT NULL AND tag IS NOT NULL -> 3,436 of 3,683
The 3,013 skipped ratings and 247 skipped tags are the injected NULLs, not
lost rows: count_data() applies the same filters, so the progress meter counts
what it intends to create and reaches 100%. A NULL *rating* is not filtered --
those 981 rows do become edges, with RATED.rating left NULL, which is why
Query 8 sums to 96,842 and not to 97,823.
Expected Results (movielens-small dataset):
==================================
✓ Vertices: 610 Users + 9,742 Movies = 10,352 total
✓ Edges: 97,823 RATED + 3,436 TAGGED = 101,259 total
Performance (movielens-small dataset):
- Java API w/ indexes + GraphBatch: ~5-10K vertices/sec, ~2-3K edges/sec
- SQL w/ indexes (sync): Slower than Java API (sequential processing)
- Without indexes: MUCH slower (no optimization)
Why `--method java` no longer uses the async executor:
======================================================
Until 2026-09-15 the Java+async path submitted one INSERT per vertex through
`async_executor().command(...)`. Measured on 26.9.1, that lost most of the
writes: 610 Users submitted, 458 stored; 9,742 Movies submitted, 2,436 stored,
with nothing raised, nothing logged at SEVERE, and wait_completion() returning
normally. The edge phase then read a graph missing three quarters of its
Movies and created 18,372 of 97,823 RATED edges. Filed as
ArcadeData/arcadedb#7615.
The Java API was never at fault -- the async executor's SQL command path is.
The path now builds vertices through GraphBatch, which dispatches its edge
flush through that same executor and is measured exact. `--method java`,
`--method java --no-async`, and `--method sql` all produce the same graph:
610 / 9,742 / 97,823 / 3,436. EdgeCreator never touched the async executor in
either method (it stores use_async and parallel_level and reads neither). CI
runs --method sql.
Usage:
======
# Recommended:
python 05_csv_import_graph.py --dataset movielens-small --method sql
# Java API with GraphBatch vertices - same graph as --method sql:
python 05_csv_import_graph.py --dataset movielens-small --method java
# Java API without async (synchronous) - correct, same graph as --method sql:
python 05_csv_import_graph.py --dataset movielens-small --method java --no-async
# Export graph database for reproducibility:
python 05_csv_import_graph.py --dataset movielens-small --method java --export
# Import from document DB export, create graph, and export result:
python 05_csv_import_graph.py --dataset movielens-small --import-jsonl ./exports/movielens_small_db.jsonl.tgz --export
# Compare all methods:
./run_benchmark_05_csv_import_graph.sh movielens-small 5000 4 all_6
# Compare all methods with export (includes roundtrip validation):
./run_benchmark_05_csv_import_graph.sh movielens-small 5000 4 all_6 --export
Export & Roundtrip Validation:
===============================
When --export is enabled:
1. Graph database is exported to JSONL (compressed)
2. Export is imported into a new database
3. All counts are verified (users, movies, edges)
4. Sample data is validated (User #1 ratings/tags)
5. Both export and import times are measured
This validates the complete cycle: graph creation → export → import → verify
"""
import argparse
import json
import os
import shutil
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import arcadedb
# Edge statements with every value bound as a ? parameter: the two endpoint
# RIDs, then the edge properties. One statement text for every edge also lets
# ArcadeDB's statement cache reuse the parse instead of parsing each row anew.
RATED_EDGE_SQL = "CREATE EDGE RATED FROM ? TO ? SET rating = ?, timestamp = ?"
TAGGED_EDGE_SQL = "CREATE EDGE TAGGED FROM ? TO ? SET tag = ?, timestamp = ?"
@dataclass
class BenchmarkStats:
"""Statistics for a single operation."""
count: int = 0
duration: float = 0.0
query_times: list[float] = None
def __post_init__(self):
if self.query_times is None:
self.query_times = []
@property
def rate(self) -> float:
"""Items per second."""
return self.count / self.duration if self.duration > 0 else 0
def add_query_time(self, elapsed: float):
"""Record a query execution time."""
self.query_times.append(elapsed)
def query_stats(self) -> tuple[float, float]:
"""Return (mean, std) of query times in seconds."""
if not self.query_times:
return 0.0, 0.0
times = np.array(self.query_times)
return float(np.mean(times)), float(np.std(times))
class DataLoader:
"""Handles paginated data loading from source database."""
def __init__(self, source_db_path: Path, batch_size: int):
self.source_db_path = source_db_path
self.batch_size = batch_size
def load_links_paginated(self) -> dict[int, dict[str, Any]]:
"""Load Link data with proper pagination (database-level streaming).
Returns dict mapping movieId -> {imdbId, tmdbId}
"""
print("Loading Link data (paginated)...")
start_time = time.time()
links_data = {}
batch_count = 0
with arcadedb.open_database(str(self.source_db_path)) as source_db:
last_rid = "#-1:-1"
while True:
query = f"""
SELECT *, @rid as rid FROM Link
WHERE @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
if not chunk:
break
for record in chunk:
movie_id = record.get("movieId")
links_data[movie_id] = {
"imdbId": (
record.get("imdbId")
if record.has_property("imdbId")
else None
),
"tmdbId": (
record.get("tmdbId")
if record.has_property("tmdbId")
else None
),
}
last_rid = chunk[-1].get("rid")
batch_count += 1
elapsed = time.time() - start_time
print(
f"✓ Loaded {len(links_data):,} links in {elapsed:.2f}s "
f"({batch_count} batches)"
)
return links_data
def count_data(self) -> tuple[int, int, int, int]:
"""Count totals: users, movies, ratings, tags."""
print("Counting data...")
with arcadedb.open_database(str(self.source_db_path)) as source_db:
# Count distinct users using subquery
result = list(
source_db.query(
"sql",
"""
SELECT COUNT(*) as count FROM (
SELECT userId FROM Rating GROUP BY userId
)
""",
)
)
total_users = result[0].get("count")
# Count movies
result = list(source_db.query("sql", "SELECT COUNT(*) as count FROM Movie"))
total_movies = result[0].get("count")
# Count ratings
result = list(
source_db.query(
"sql",
"SELECT COUNT(*) as count FROM Rating WHERE timestamp IS NOT NULL",
)
)
total_ratings = result[0].get("count")
# Count tags
result = list(
source_db.query(
"sql",
"SELECT COUNT(*) as count FROM Tag "
"WHERE timestamp IS NOT NULL AND tag IS NOT NULL",
)
)
total_tags = result[0].get("count")
print(
f"✓ Found {total_users:,} users, {total_movies:,} movies, "
f"{total_ratings:,} ratings, {total_tags:,} tags"
)
return total_users, total_movies, total_ratings, total_tags
class VertexCreator:
"""Creates vertices using either Java API or SQL."""
def __init__(
self,
db: Any,
data_loader: DataLoader,
batch_size: int,
parallel_level: int = 4,
use_java_api: bool = True,
use_async: bool = True,
):
self.db = db
self.data_loader = data_loader
self.batch_size = batch_size
self.parallel_level = parallel_level
self.use_java_api = use_java_api
self.use_async = use_async
def create_all_vertices(
self, total_users: int, total_movies: int, links_data: dict
) -> tuple[int, int, BenchmarkStats, BenchmarkStats]:
"""Create all User and Movie vertices.
Returns: (user_count, movie_count, user_stats, movie_stats)
"""
user_count, user_stats = self._create_users(total_users)
movie_count, movie_stats = self._create_movies(total_movies, links_data)
return user_count, movie_count, user_stats, movie_stats
def _create_users(self, total_users: int) -> tuple[int, BenchmarkStats]:
"""Create User vertices.
Note: reads the user ids with GROUP BY, which runs in the parallel scan
workers; a SELECT DISTINCT with this ORDER BY would not (ArcadeData/arcadedb#8799).
An earlier direct DISTINCT/ORDER BY form
resolved against the wrong database while the target graph DB was open
beside the source document DB; the GROUP BY form was checked with both
open, in all three creation modes, on 2026-10-01.
"""
print(f"Creating {total_users:,} User vertices...")
stats = BenchmarkStats()
start_time = time.time()
user_count = 0
batch_count = 0
if self.use_async and self.use_java_api:
# GraphBatch path. This used to submit one INSERT per user through
# async_executor().command(); see the "Bulk vertex path" note in the
# module docstring for why it does not any more.
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
query = "SELECT userId FROM Rating GROUP BY userId ORDER BY userId"
pending: list[dict[str, Any]] = []
# WAL off (use_wal=False, GraphBatch's default): this example rebuilds its database from
# the source files, so a crash mid-import costs a re-run. An import that must survive a
# crash passes use_wal=True (ArcadeDB's recommendation, ArcadeData/arcadedb#8287).
with self.db.graph_batch(
parallel_flush=self.parallel_level > 1
) as batch:
def flush_users(rows):
nonlocal user_count, batch_count
created = batch.create_vertices("User", rows)
if len(created) != len(rows):
raise RuntimeError(
f"GraphBatch returned {len(created)} RIDs for "
f"{len(rows)} User rows"
)
user_count += len(created)
batch_count += 1
self._report_progress(
"User",
batch_count,
user_count,
total_users,
start_time,
)
for record in source_db.query("sql", query):
pending.append({"userId": record.get("userId")})
if len(pending) >= self.batch_size:
flush_users(pending)
pending = []
if pending:
flush_users(pending)
elif self.use_java_api:
# Java API without async (synchronous transactions)
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
query = "SELECT userId FROM Rating GROUP BY userId ORDER BY userId"
batch_user_ids = []
for record in source_db.query("sql", query):
user_id = record.get("userId")
batch_user_ids.append(user_id)
if len(batch_user_ids) >= self.batch_size:
with self.db.transaction():
for uid in batch_user_ids:
self.db.command(
"sql", "INSERT INTO User SET userId = ?", uid
)
user_count += len(batch_user_ids)
batch_count += 1
batch_user_ids = []
self._report_progress(
"User", batch_count, user_count, total_users, start_time
)
# Handle remaining
if batch_user_ids:
with self.db.transaction():
for uid in batch_user_ids:
self.db.command(
"sql", "INSERT INTO User SET userId = ?", uid
)
user_count += len(batch_user_ids)
batch_count += 1
else:
# SQL mode (always synchronous for vertices - async causes
# ConcurrentModificationException due to multiple threads writing
# to same pages)
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
query = "SELECT userId FROM Rating GROUP BY userId ORDER BY userId"
batch_user_ids = []
for record in source_db.query("sql", query):
user_id = record.get("userId")
batch_user_ids.append(user_id)
if len(batch_user_ids) >= self.batch_size:
with self.db.transaction():
for uid in batch_user_ids:
self.db.command(
"sql", "INSERT INTO User SET userId = ?", uid
)
user_count += len(batch_user_ids)
batch_count += 1
batch_user_ids = []
self._report_progress(
"User", batch_count, user_count, total_users, start_time
)
# Handle remaining
if batch_user_ids:
with self.db.transaction():
for uid in batch_user_ids:
self.db.command(
"sql", "INSERT INTO User SET userId = ?", uid
)
user_count += len(batch_user_ids)
batch_count += 1
stats.count = user_count
stats.duration = time.time() - start_time
print(f"✓ Created {user_count:,} User vertices")
print(f" ⏱️ {stats.duration:.2f}s ({stats.rate:.0f} vertices/sec)")
print()
return user_count, stats
def _create_movies(
self, total_movies: int, links_data: dict
) -> tuple[int, BenchmarkStats]:
"""Create Movie vertices with pagination (database-level streaming)."""
print(f"Creating {total_movies:,} Movie vertices...")
stats = BenchmarkStats()
start_time = time.time()
movie_count = 0
batch_count = 0
if self.use_async and self.use_java_api:
# GraphBatch path, for the same reason as _create_users above.
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
last_rid = "#-1:-1"
# WAL off (use_wal=False, GraphBatch's default): this example rebuilds its database from
# the source files, so a crash mid-import costs a re-run. An import that must survive a
# crash passes use_wal=True (ArcadeDB's recommendation, ArcadeData/arcadedb#8287).
with self.db.graph_batch(
parallel_flush=self.parallel_level > 1
) as batch:
while True:
query_start = time.time()
query = f"""
SELECT *, @rid as rid FROM Movie
WHERE @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
query_time = time.time() - query_start
stats.add_query_time(query_time)
if not chunk:
break
rows = []
for record in chunk:
movie_id = record.get("movieId")
title = (
record.get("title")
if record.has_property("title")
else ""
)
genres = (
record.get("genres")
if record.has_property("genres")
else ""
)
props = {
"movieId": movie_id,
"title": title or "",
"genres": genres or "",
}
link_data = links_data.get(movie_id)
if link_data:
if link_data["imdbId"] is not None:
props["imdbId"] = link_data["imdbId"]
if link_data["tmdbId"] is not None:
props["tmdbId"] = link_data["tmdbId"]
rows.append(props)
created = batch.create_vertices("Movie", rows)
if len(created) != len(rows):
raise RuntimeError(
f"GraphBatch returned {len(created)} RIDs for "
f"{len(rows)} Movie rows"
)
movie_count += len(created)
batch_count += 1
last_rid = chunk[-1].get("rid")
self._report_progress(
"Movie",
batch_count,
movie_count,
total_movies,
start_time,
query_time,
)
elif self.use_java_api:
# Java API without async (synchronous transactions)
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
last_rid = "#-1:-1"
while True:
query_start = time.time()
query = f"""
SELECT *, @rid as rid FROM Movie
WHERE @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
query_time = time.time() - query_start
stats.add_query_time(query_time)
if not chunk:
break
with self.db.transaction():
for record in chunk:
movie_id = record.get("movieId")
title = (
record.get("title")
if record.has_property("title")
else ""
)
genres = (
record.get("genres")
if record.has_property("genres")
else ""
)
# Merge Link data
props = {
"movieId": movie_id,
"title": title or "",
"genres": genres or "",
}
link_data = links_data.get(movie_id)
if link_data:
if link_data["imdbId"] is not None:
props["imdbId"] = link_data["imdbId"]
if link_data["tmdbId"] is not None:
props["tmdbId"] = link_data["tmdbId"]
assignments = ", ".join(f"{key} = ?" for key in props)
values = [props[key] for key in props]
self.db.command(
"sql",
f"INSERT INTO Movie SET {assignments}",
*values,
)
movie_count += len(chunk)
batch_count += 1
last_rid = chunk[-1].get("rid")
self._report_progress(
"Movie",
batch_count,
movie_count,
total_movies,
start_time,
query_time,
)
else:
# SQL INSERT in batched transactions
with arcadedb.open_database(
str(self.data_loader.source_db_path)
) as source_db:
last_rid = "#-1:-1"
while True:
query_start = time.time()
query = f"""
SELECT *, @rid as rid FROM Movie
WHERE @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
query_time = time.time() - query_start
stats.add_query_time(query_time)
if not chunk:
break
with self.db.transaction():
for record in chunk:
movie_id = record.get("movieId")
title = (
record.get("title")
if record.has_property("title")
else ""
)
genres = (
record.get("genres")
if record.has_property("genres")
else ""
)
# Values are bound as ? parameters, never pasted
# into the SQL text, so titles need no escaping
sql = (
"INSERT INTO Movie SET "
"movieId = ?, title = ?, genres = ?"
)
values = [movie_id, title or "", genres or ""]
# Merge Link data
link_data = links_data.get(movie_id)
if link_data:
if link_data["imdbId"] is not None:
sql += ", imdbId = ?"
values.append(str(link_data["imdbId"]))
if link_data["tmdbId"] is not None:
sql += ", tmdbId = ?"
values.append(link_data["tmdbId"])
self.db.command("sql", sql, *values)
movie_count += len(chunk)
batch_count += 1
last_rid = chunk[-1].get("rid")
self._report_progress(
"Movie",
batch_count,
movie_count,
total_movies,
start_time,
query_time,
)
stats.count = movie_count
stats.duration = time.time() - start_time
print(f"✓ Created {movie_count:,} Movie vertices")
print(f" ⏱️ {stats.duration:.2f}s ({stats.rate:.0f} vertices/sec)")
mean, std = stats.query_stats()
if stats.query_times:
print(
f" Query times: {mean:.2f} ± {std:.2f}s "
f"({len(stats.query_times)} queries)"
)
print()
return movie_count, stats
def _report_progress(
self,
entity_type: str,
batch_num: int,
current: int,
total: int,
start_time: float,
query_time: float = None,
):
"""Print progress report."""
elapsed = time.time() - start_time
if elapsed > 0:
rate = current / elapsed
remaining = total - current
pct = (current / total) * 100 if total > 0 else 0
progress_msg = (
f" Batch {batch_num}: {current:,}/{total:,} "
f"{entity_type}s ({pct:.1f}%, {remaining:,} remaining, "
f"{rate:.0f}/sec)"
)
if query_time is not None:
progress_msg += f", query: {query_time:.2f}s"
print(progress_msg)
class EdgeCreator:
"""Creates edges using either Java API or SQL."""
def __init__(
self,
db: Any,
data_loader: DataLoader,
batch_size: int,
use_java_api: bool = True,
has_indexes: bool = True,
use_async: bool = True,
parallel_level: int = 4,
):
self.db = db
self.data_loader = data_loader
self.batch_size = batch_size
self.use_java_api = use_java_api
self.has_indexes = has_indexes
self.use_async = use_async
self.parallel_level = parallel_level
def create_all_edges(
self, total_ratings: int, total_tags: int
) -> tuple[int, int, BenchmarkStats, BenchmarkStats]:
"""Create all RATED and TAGGED edges.
Returns: (rated_count, tagged_count, rated_stats, tagged_stats)
"""
rated_count, rated_stats = self._create_rated_edges(total_ratings)
tagged_count, tagged_stats = self._create_tagged_edges(total_tags)
return rated_count, tagged_count, rated_stats, tagged_stats
def _create_rated_edges(self, total_ratings: int) -> tuple[int, BenchmarkStats]:
"""Create RATED edges with pagination (database-level streaming)."""
print(f"Creating {total_ratings:,} RATED edges...")
stats = BenchmarkStats()
start_time = time.time()
edge_count = 0
batch_count = 0
with arcadedb.open_database(str(self.data_loader.source_db_path)) as source_db:
last_rid = "#-1:-1"
while True:
# Load batch of ratings
query_start = time.time()
query = f"""
SELECT *, @rid as rid FROM Rating
WHERE timestamp IS NOT NULL AND @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
query_time = time.time() - query_start
stats.add_query_time(query_time)
if not chunk:
break
with self.db.transaction():
# Build vertex cache for this batch
cache_start = time.time()
user_cache, movie_cache = self._build_vertex_cache(chunk)
cache_time = time.time() - cache_start
stats.add_query_time(cache_time)
# Create edges
for record in chunk:
user_id = record.get("userId")
movie_id = record.get("movieId")
rating = record.get("rating")
timestamp = record.get("timestamp")
if self.use_java_api:
user_vertex = user_cache.get(user_id)
movie_vertex = movie_cache.get(movie_id)
if user_vertex and movie_vertex:
user_rid = str(user_vertex.get_identity())
movie_rid = str(movie_vertex.get_identity())
self.db.command(
"sql",
RATED_EDGE_SQL,
user_rid,
movie_rid,
rating,
timestamp,
)
edge_count += 1
else:
# SQL CREATE EDGE
user_rid = user_cache.get(user_id)
movie_rid = movie_cache.get(movie_id)
if user_rid and movie_rid:
self.db.command(
"sql",
RATED_EDGE_SQL,
user_rid,
movie_rid,
rating,
timestamp,
)
edge_count += 1
batch_count += 1
last_rid = chunk[-1].get("rid")
total_query_time = query_time + cache_time
self._report_progress(
"RATED",
batch_count,
edge_count,
total_ratings,
start_time,
total_query_time,
)
stats.count = edge_count
stats.duration = time.time() - start_time
print(f"✓ Created {edge_count:,} RATED edges")
print(f" ⏱️ {stats.duration:.2f}s ({stats.rate:.0f} edges/sec)")
mean, std = stats.query_stats()
if stats.query_times:
print(
f" Query times: {mean:.2f} ± {std:.2f}s "
f"({len(stats.query_times)} queries)"
)
print()
return edge_count, stats
def _create_tagged_edges(self, total_tags: int) -> tuple[int, BenchmarkStats]:
"""Create TAGGED edges with pagination (database-level streaming)."""
print(f"Creating {total_tags:,} TAGGED edges...")
stats = BenchmarkStats()
start_time = time.time()
edge_count = 0
batch_count = 0
with arcadedb.open_database(str(self.data_loader.source_db_path)) as source_db:
last_rid = "#-1:-1"
while True:
# Load batch of tags
query_start = time.time()
query = f"""
SELECT *, @rid as rid FROM Tag
WHERE timestamp IS NOT NULL
AND tag IS NOT NULL
AND @rid > {last_rid}
LIMIT {self.batch_size}
"""
chunk = list(source_db.query("sql", query))
query_time = time.time() - query_start
stats.add_query_time(query_time)
if not chunk:
break
with self.db.transaction():
# Build vertex cache for this batch
cache_start = time.time()
user_cache, movie_cache = self._build_vertex_cache(chunk)
cache_time = time.time() - cache_start
stats.add_query_time(cache_time)
# Create edges
for record in chunk:
user_id = record.get("userId")
movie_id = record.get("movieId")
tag = record.get("tag") or ""
timestamp = record.get("timestamp")
if self.use_java_api:
user_vertex = user_cache.get(user_id)
movie_vertex = movie_cache.get(movie_id)
if user_vertex and movie_vertex:
user_rid = str(user_vertex.get_identity())
movie_rid = str(movie_vertex.get_identity())
self.db.command(
"sql",
TAGGED_EDGE_SQL,
user_rid,
movie_rid,
tag,
timestamp,
)
edge_count += 1
else:
# SQL CREATE EDGE
user_rid = user_cache.get(user_id)
movie_rid = movie_cache.get(movie_id)
if user_rid and movie_rid:
self.db.command(
"sql",
TAGGED_EDGE_SQL,
user_rid,
movie_rid,
tag,
timestamp,
)
edge_count += 1
batch_count += 1
last_rid = chunk[-1].get("rid")
total_query_time = query_time + cache_time
self._report_progress(
"TAGGED",
batch_count,
edge_count,
total_tags,
start_time,
total_query_time,
)
stats.count = edge_count
stats.duration = time.time() - start_time
print(f"✓ Created {edge_count:,} TAGGED edges")
print(f" ⏱️ {stats.duration:.2f}s ({stats.rate:.0f} edges/sec)")
mean, std = stats.query_stats()
if stats.query_times:
print(
f" Query times: {mean:.2f} ± {std:.2f}s "
f"({len(stats.query_times)} queries)"
)
print()
return edge_count, stats
def _build_vertex_cache(self, chunk: list) -> tuple[dict, dict]:
"""Build vertex cache for a batch of records.
For Java API: Returns (user_vertices, movie_vertices)
For SQL: Returns (user_rids, movie_rids)
"""
user_ids = list({r.get("userId") for r in chunk})
movie_ids = list({r.get("movieId") for r in chunk})
user_cache = {}
movie_cache = {}
if self.use_java_api:
# Fetch Java vertex objects
# The ids travel as one list parameter, so every chunk runs the
# same query text and ArcadeDB reuses its plan (it still reads the
# userId index for `IN :ids`).
if user_ids:
query = "SELECT FROM User WHERE userId IN :ids"
for result in self.db.query("sql", query, {"ids": user_ids}):
uid = result.get("userId")
vertex = result.get_vertex()
user_cache[uid] = vertex
if movie_ids:
query = "SELECT FROM Movie WHERE movieId IN :ids"
for result in self.db.query("sql", query, {"ids": movie_ids}):
mid = result.get("movieId")
vertex = result.get_vertex()
movie_cache[mid] = vertex
else:
# Fetch RIDs for SQL CREATE EDGE
if user_ids:
query = "SELECT @rid as rid, userId FROM User WHERE userId IN :ids"
for result in self.db.query("sql", query, {"ids": user_ids}):
uid = result.get("userId")
rid = result.get("rid").toString()
user_cache[uid] = rid
if movie_ids:
query = "SELECT @rid as rid, movieId FROM Movie WHERE movieId IN :ids"
for result in self.db.query("sql", query, {"ids": movie_ids}):
mid = result.get("movieId")
rid = result.get("rid").toString()
movie_cache[mid] = rid
return user_cache, movie_cache
def _report_progress(
self,
edge_type: str,
batch_num: int,
current: int,
total: int,
start_time: float,
query_time: float = None,
):