Repository navigation
Expand file tree
/
Copy path03_vector_search.py
More file actions
518 lines (448 loc) · 19.2 KB
/
Copy path03_vector_search.py
File metadata and controls
518 lines (448 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
#!/usr/bin/env python3
"""
Example 03: Vector Search - Semantic Similarity
This example demonstrates vector embeddings and semantic similarity search using
ArcadeDB's HNSW (JVector) index.
Key Concepts:
- Storing vector embeddings (simulated sentence embeddings)
- Creating HNSW (JVector) indexes for fast nearest-neighbor search
- Finding semantically similar documents using cosine similarity
- Understanding vector search parameters (dimensions, distance functions)
- INT8-encoded dense-vector storage for smaller payloads and bucket footprint
- Sparse-vector indexing for token/weight retrieval workloads
- Index population strategies and performance characteristics
Implementation: LSM_VECTOR indexes are built on datastax/jvector.
Use Cases:
- Semantic document search (find similar articles, papers)
- RAG (Retrieval-Augmented Generation) for LLMs
- Recommendation systems (find similar products, content)
- Duplicate detection (find near-duplicate text)
- Question answering (find relevant context)
Requirements:
- arcadedb
- NumPy (for vector operations and mock embeddings)
Note: This example uses mock embeddings for demonstration. In production:
- Use real embedding models (OpenAI, sentence-transformers, etc.)
- Store higher-dimensional vectors (384, 768, 1536 dimensions)
- Index vectors incrementally as you insert documents
- Consider metadata filtering strategies (see documentation)
About Vector Search:
Vector embeddings represent text/images as points in high-dimensional space.
Similar items are close together, enabling semantic search beyond keyword matching.
HNSW (JVector) enables logarithmic search time without loading all vectors into memory.
"""
import argparse
import os
import shutil
import time
import zlib
import jpype.types as jtypes
import numpy as np
import arcadedb
# Parse command line arguments
parser = argparse.ArgumentParser(
description="Example 03: Vector Search - Semantic Similarity"
)
args = parser.parse_args()
print("=" * 70)
print("🔍 ArcadeDB Python - Example 03: Vector Search (JVector)")
print("=" * 70)
print()
# -----------------------------------------------------------------------------
# Step 1: Create Database
# -----------------------------------------------------------------------------
print("Step 1: Creating database...")
step_start = time.time()
db_dir = "./my_test_databases"
db_path = os.path.join(db_dir, "vector_search_db")
# Clean up any existing database
if os.path.exists(db_path):
shutil.rmtree(db_path)
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(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 2: Define Schema
# -----------------------------------------------------------------------------
print("Step 2: Defining schema...")
step_start = time.time()
# Create vertex type for documents
db.command("sql", "CREATE VERTEX TYPE Article")
# Create properties
# Note: Vector property MUST be ARRAY_OF_FLOATS
db.command("sql", "CREATE PROPERTY Article.title STRING")
db.command("sql", "CREATE PROPERTY Article.content STRING")
db.command("sql", "CREATE PROPERTY Article.category STRING")
db.command("sql", "CREATE PROPERTY Article.embedding ARRAY_OF_FLOATS")
db.command("sql", "CREATE PROPERTY Article.id STRING")
# Create standard index on ID for fast lookups
db.command("sql", "CREATE INDEX ON Article (id) UNIQUE_HASH")
print(" ✅ Schema created: Article vertex type")
print(" 💡 Vector property type: ARRAY_OF_FLOATS")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 3: Generate Mock Data
# -----------------------------------------------------------------------------
print("Step 3: Generating mock data...")
step_start = time.time()
# Configuration
NUM_DOCUMENTS = 10000
EMBEDDING_DIM = 384 # Typical for small transformer models
NUM_CATEGORIES = 50
def create_mock_embedding(category_seed, doc_seed):
"""
Create a deterministic mock embedding based on category and document seeds.
Documents in the same category will be closer together.
"""
# Deterministic random state. zlib.crc32 gives the same seed in every
# process; Python's hash() of a str is randomized per process
# (PYTHONHASHSEED), which made the embeddings differ from run to run.
rng = np.random.RandomState(zlib.crc32((category_seed + doc_seed).encode()))
# Base vector for the category (random direction)
cat_rng = np.random.RandomState(zlib.crc32(category_seed.encode()))
category_vector = cat_rng.randn(EMBEDDING_DIM)
category_vector /= np.linalg.norm(category_vector)
# Add noise for the specific document
noise = rng.randn(EMBEDDING_DIM) * 0.2 # 20% noise
# Combine and normalize
embedding = category_vector + noise
embedding /= np.linalg.norm(embedding)
return embedding.astype(np.float32)
def quantize_to_int8_bytes(vector: np.ndarray):
"""Quantize a normalized float vector to signed int8 bytes."""
scaled = np.clip(np.rint(vector * 127.0), -127, 127).astype(np.int8)
return scaled.tolist()
# Generate documents
documents = []
for i in range(NUM_DOCUMENTS):
cat_id = (i % NUM_CATEGORIES) + 1
category = f"category_{cat_id}"
doc_id = f"doc_{i}"
embedding = create_mock_embedding(category, doc_id)
documents.append(
{
"id": doc_id,
"title": f"Article {i} about {category}",
"content": f"This is the content for article {i} in {category}...",
"category": category,
# KEEP THE NUMPY ARRAY. to_java_float_array (used at insertion
# below) takes NumPy directly and has a fast path for it; going
# through a Python list first costs 2.2x in conversion alone --
# 16.5 us against 7.5 us per vector at 384 dimensions -- and
# buys nothing, since nothing here needs the list.
"embedding": embedding,
}
)
print(f" ✅ Generated {NUM_DOCUMENTS} mock documents")
print(f" 💡 Embedding dimensions: {EMBEDDING_DIM}")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 4: Insert Data
# -----------------------------------------------------------------------------
print("Step 4: Inserting data...")
step_start = time.time()
# Per-row inserts inside one transaction; BATCH_SIZE only paces the
# progress output (for true batched ingest see example 22 / insert_many)
BATCH_SIZE = 1000
total_inserted = 0
with db.transaction():
for i, doc in enumerate(documents):
db.command(
"sql",
"""
INSERT INTO Article SET
id = :id,
title = :title,
content = :content,
category = :category,
embedding = :embedding
""",
{
"id": doc["id"],
"title": doc["title"],
"content": doc["content"],
"category": doc["category"],
"embedding": arcadedb.to_java_float_array(doc["embedding"]),
},
)
total_inserted += 1
# Commit batch
if total_inserted % BATCH_SIZE == 0:
db.commit()
db.begin()
print(f" Inserted {total_inserted}/{NUM_DOCUMENTS} documents...")
print(f" ✅ Inserted {total_inserted} documents")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 5: Create Vector Index
# -----------------------------------------------------------------------------
print("Step 5: Creating vector index...")
step_start = time.time()
db.command(
"sql",
f"""
CREATE INDEX ON Article (embedding)
LSM_VECTOR
METADATA {{
"dimensions": {EMBEDDING_DIM},
"similarity": "COSINE"
}}
""",
)
# Report what the index was actually built with. The METADATA above sets only
# dimensions and similarity, so everything else comes from the engine defaults;
# reading them back keeps this output correct if those defaults change.
index_meta = db.schema.get_vector_index("Article", "embedding").get_metadata()
print(" 💡 JVector Parameters:")
print(f" • dimensions: {index_meta['dimensions']} (matches embedding size)")
print(
f" • distance_function: {index_meta['similarity_function']}"
" (best for normalized vectors)"
)
print(
f" • max_connections: {index_meta['max_connections']}"
" (connections per node, higher = more accurate but slower)"
)
print(
f" • beam_width: {index_meta['beam_width']}"
" (search quality, higher = more accurate)"
)
print()
print(" ✅ Created JVector vector index")
print(" ✅ Built vector index graph immediately via SQL")
print(" 💡 LSM index automatically indexes existing records upon creation.")
print(" ✅ Indexing handled by ArcadeDB engine.")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 6: Perform Semantic Search
# -----------------------------------------------------------------------------
print("Step 6: Performing semantic similarity searches...")
step_start = time.time()
# Sample 10 random categories (or NUM_CATEGORIES if less than 10)
num_queries = min(10, NUM_CATEGORIES)
sampled_categories = np.random.choice(
range(1, NUM_CATEGORIES + 1), size=num_queries, replace=False
)
print(f" Running {num_queries} queries on randomly sampled categories...")
print()
for query_num, cat_num in enumerate(sampled_categories, 1):
category = f"category_{cat_num}"
index_name = "Article[embedding]"
print(f" 🔍 Query {query_num}: Find documents similar to Category {cat_num}")
print()
query_embedding = create_mock_embedding(category, f"query{query_num}")
most_similar = db.query(
"sql",
(
"SELECT title, category, distance, (1 - distance) AS score "
"FROM (SELECT expand(vectorNeighbors(?, ?, ?))) ORDER BY distance"
),
index_name,
query_embedding,
5,
).to_list()
print(" Top 5 MOST similar documents (smallest distance):")
for i, hit in enumerate(most_similar, 1):
title = hit.get("title")
doc_category = hit.get("category")
distance = hit.get("distance")
print(f" {i}. {title}")
print(f" Category: {doc_category}, Distance: {distance:.4f}")
print()
filtered_hits = db.query(
"sql",
(
"SELECT title, category, distance, (1 - distance) AS score "
"FROM (SELECT expand(vectorNeighbors(?, ?, ?))) "
"WHERE category = ? ORDER BY distance LIMIT 5"
),
index_name,
query_embedding,
50,
category,
).to_list()
print(" Top 5 filtered documents in the same category:")
for i, hit in enumerate(filtered_hits, 1):
title = hit.get("title")
doc_category = hit.get("category")
distance = hit.get("distance")
score = hit.get("score")
print(f" {i}. {title}")
print(
f" Category: {doc_category}, Distance: {distance:.4f}, "
f"Score: {score:.4f}"
)
print()
print(f" ⏱️ All queries time: {time.time() - step_start:.3f}s")
print()
# ---------------------------------------------------------------------------
# First pass versus second pass
# ---------------------------------------------------------------------------
# ArcadeDB pages its vector index in from disk on demand, so the first time a
# query set runs it pays for the pages it touches and the second time it
# finds them resident. Engines that hold the index in memory do not move
# between passes. The project page measures this at ten million vectors
# (a first pass of ~9 ms, a repeat of ~1 ms); at 10,000 documents the effect
# is small but the shape is the same. Fresh query vectors, so pass 1 really
# is their first search.
print("🔁 Step 5b: First pass versus second pass over one query set")
pass_queries = [
create_mock_embedding(f"category_{c}", f"pass-query-{i}")
for i, c in enumerate(
np.random.choice(range(1, NUM_CATEGORIES + 1), size=20, replace=True)
)
]
pass_ms = []
pass_hits = []
for pass_no in (1, 2):
hits = []
t0 = time.perf_counter()
for q in pass_queries:
rows = db.query(
"sql",
"SELECT title FROM (SELECT expand(vectorNeighbors(?, ?, ?)))",
"Article[embedding]",
q,
5,
).to_list()
hits.append([r.get("title") for r in rows])
pass_ms.append((time.perf_counter() - t0) * 1000 / len(pass_queries))
pass_hits.append(hits)
same = sum(1 for a, b in zip(*pass_hits) if a == b)
print(
f" pass 1 (cold): {pass_ms[0]:.2f} ms per query; pass 2 (warm): {pass_ms[1]:.2f} ms per query"
)
print(
f" identical top-5 on {same}/{len(pass_queries)} queries; the second pass is faster because the index pages are resident, not because the answer changed"
)
print()
# -----------------------------------------------------------------------------
# Step 7: INT8-Encoded Dense Vectors
# -----------------------------------------------------------------------------
print("Step 7: Demonstrating INT8-encoded dense-vector storage...")
step_start = time.time()
try:
db.command("sql", "CREATE VERTEX TYPE Int8Article")
db.command("sql", "CREATE PROPERTY Int8Article.id STRING")
db.command("sql", "CREATE PROPERTY Int8Article.category STRING")
db.command("sql", "CREATE PROPERTY Int8Article.embedding BINARY")
db.command(
"sql",
"""
CREATE INDEX ON Int8Article (embedding)
LSM_VECTOR
METADATA {
"dimensions": 4,
"similarity": "COSINE",
"quantization": "NONE",
"encoding": "INT8"
}
""",
)
int8_docs = [
("int8_doc_1", "technology", [1.0, 0.0, 0.0, 0.0]),
("int8_doc_2", "technology", [0.95, 0.05, 0.0, 0.0]),
("int8_doc_3", "sports", [0.0, 1.0, 0.0, 0.0]),
]
with db.transaction():
for doc_id, category, vector in int8_docs:
db.command(
"sql",
"INSERT INTO Int8Article SET id = ?, category = ?, embedding = ?",
doc_id,
category,
arcadedb.to_java_byte_array(
quantize_to_int8_bytes(np.array(vector))
),
)
int8_hits = db.query(
"sql",
(
"SELECT id, category, distance FROM "
"(SELECT expand(vectorNeighbors('Int8Article[embedding]', ?, 2))) "
"ORDER BY distance"
),
arcadedb.to_java_float_array([1.0, 0.0, 0.0, 0.0]),
).to_list()
except arcadedb.ArcadeDBError as exc:
print(" ⚠️ Skipping INT8-encoded dense-vector demo in this runtime")
print(f" 💡 Reason: {exc}")
else:
print(" ✅ Created INT8-encoded dense index on a BINARY property")
print(" 💡 Use this when your embeddings are already stored as int8 bytes")
print(" Top matches for [1, 0, 0, 0]:")
for hit in int8_hits:
print(
f" • {hit.get('id')} ({hit.get('category')}), "
f"distance={hit.get('distance'):.4f}"
)
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Step 8: Sparse Vectors
# -----------------------------------------------------------------------------
print("Step 8: Demonstrating sparse-vector retrieval...")
step_start = time.time()
try:
db.command("sql", "CREATE DOCUMENT TYPE SparseArticle")
db.command("sql", "CREATE PROPERTY SparseArticle.id STRING")
db.command("sql", "CREATE PROPERTY SparseArticle.tokens ARRAY_OF_INTEGERS")
db.command("sql", "CREATE PROPERTY SparseArticle.weights ARRAY_OF_FLOATS")
db.command(
"sql",
"""
CREATE INDEX ON SparseArticle (tokens, weights)
LSM_SPARSE_VECTOR
METADATA {
"dimensions": 128
}
""",
)
with db.transaction():
db.command(
"sql",
"INSERT INTO SparseArticle SET id = 'sparse_doc_1', tokens = [1, 5, 10], weights = [0.5, 0.3, 0.2]",
)
db.command(
"sql",
"INSERT INTO SparseArticle SET id = 'sparse_doc_2', tokens = [2, 5, 11], weights = [0.4, 0.6, 0.1]",
)
sparse_hits = db.query(
"sql",
(
"SELECT id, score FROM "
"(SELECT expand(`vector.sparseNeighbors`('SparseArticle[tokens,weights]', ?, ?, 5))) "
"ORDER BY score DESC"
),
jtypes.JArray(jtypes.JInt)([5]),
arcadedb.to_java_float_array([1.0]),
).to_list()
except arcadedb.ArcadeDBError as exc:
print(" ⚠️ Skipping sparse-vector demo in this runtime")
print(f" 💡 Reason: {exc}")
else:
print(" ✅ Created sparse-vector index on token/weight arrays")
print(" 💡 Use this for BM25-style or learned sparse retrieval")
print(" Top matches for sparse query {(5): 1.0}:")
for hit in sparse_hits:
print(f" • {hit.get('id')}, score={hit.get('score'):.4f}")
print(f" ⏱️ Time: {time.time() - step_start:.3f}s")
print()
# -----------------------------------------------------------------------------
# Cleanup
# -----------------------------------------------------------------------------
print("=" * 70)
print("✅ Vector search example completed successfully!")
print("=" * 70)
print()
db.close()
print(f"💡 Database preserved at: {db_path}")
print()