Skip to content

Commit fbf0d6e

Browse files
committed
feat(examples): add usage examples for sqlite-vec-client
* Implement basic usage example * Add batch operations example * Create context manager example * Include metadata filtering example * Add persistent database example * Implement real-world scenario example
1 parent 10a4369 commit fbf0d6e

File tree

7 files changed

+404
-5
lines changed

7 files changed

+404
-5
lines changed

TODO

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
- [ ] Mock tests (sqlite-vec extension)
2626

2727
### Examples
28-
- [ ] examples/basic_usage.py
29-
- [ ] examples/metadata_filtering.py
30-
- [ ] examples/batch_operations.py
31-
- [ ] examples/context_manager.py
32-
- [ ] examples/real_world_scenario.py
28+
- [x] examples/basic_usage.py
29+
- [x] examples/metadata_filtering.py
30+
- [x] examples/batch_operations.py
31+
- [x] examples/context_manager.py
32+
- [x] examples/real_world_scenario.py
3333

3434
### Documentation
3535
- [ ] Create CONTRIBUTING.md

examples/basic_usage.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""Basic usage example for sqlite-vec-client.
2+
3+
Demonstrates:
4+
- Creating a client and table
5+
- Adding texts with embeddings
6+
- Similarity search
7+
- Retrieving records
8+
"""
9+
10+
from sqlite_vec_client import SQLiteVecClient
11+
12+
13+
def main():
14+
# Initialize client
15+
client = SQLiteVecClient(table="documents", db_path=":memory:")
16+
17+
# Create table with 384-dimensional embeddings
18+
client.create_table(dim=384, distance="cosine")
19+
20+
# Sample texts and embeddings (384-dim vectors)
21+
texts = [
22+
"The quick brown fox jumps over the lazy dog",
23+
"Machine learning is a subset of artificial intelligence",
24+
"Python is a popular programming language",
25+
]
26+
27+
embeddings = [
28+
[0.1, 0.2, 0.3] + [0.0] * 381,
29+
[0.5, 0.4, 0.3] + [0.0] * 381,
30+
[0.2, 0.1, 0.05] + [0.0] * 381,
31+
]
32+
33+
# Add records
34+
rowids = client.add(texts=texts, embeddings=embeddings)
35+
print(f"Added {len(rowids)} records: {rowids}")
36+
37+
# Similarity search
38+
query_embedding = [0.1, 0.2, 0.3] + [0.0] * 381
39+
results = client.similarity_search(embedding=query_embedding, top_k=2)
40+
41+
print("\nTop 2 similar documents:")
42+
for rowid, text, distance in results:
43+
print(f" [{rowid}] {text[:50]}... (distance: {distance:.4f})")
44+
45+
# Get record by ID
46+
record = client.get_by_id(rowids[0])
47+
if record:
48+
rowid, text, metadata, embedding = record
49+
print(f"\nRecord {rowid}: {text}")
50+
51+
# Count total records
52+
print(f"\nTotal records: {client.count()}")
53+
54+
client.close()
55+
56+
57+
if __name__ == "__main__":
58+
main()

examples/batch_operations.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""Batch operations example for sqlite-vec-client.
2+
3+
Demonstrates:
4+
- Bulk insert
5+
- Batch retrieval
6+
- Pagination
7+
- Bulk delete
8+
"""
9+
10+
from sqlite_vec_client import SQLiteVecClient
11+
12+
13+
def main():
14+
client = SQLiteVecClient(table="products", db_path=":memory:")
15+
client.create_table(dim=64, distance="L2")
16+
17+
# Bulk insert
18+
num_products = 100
19+
texts = [f"Product {i} description" for i in range(num_products)]
20+
embeddings = [[float(i % 10) / 10] * 64 for i in range(num_products)]
21+
metadata = [{"product_id": i, "price": i * 10} for i in range(num_products)]
22+
23+
rowids = client.add(texts=texts, embeddings=embeddings, metadata=metadata)
24+
print(f"Inserted {len(rowids)} products")
25+
26+
# Pagination - list first page
27+
page_size = 10
28+
page_1 = client.list_results(limit=page_size, offset=0, order="asc")
29+
print(f"\nPage 1 ({len(page_1)} items):")
30+
for rowid, text, meta, _ in page_1[:3]:
31+
print(f" [{rowid}] {text} - ${meta['price']}")
32+
33+
# Pagination - list second page
34+
page_2 = client.list_results(limit=page_size, offset=page_size, order="asc")
35+
print(f"\nPage 2 ({len(page_2)} items):")
36+
for rowid, text, meta, _ in page_2[:3]:
37+
print(f" [{rowid}] {text} - ${meta['price']}")
38+
39+
# Batch retrieval
40+
selected_ids = rowids[10:15]
41+
selected_products = client.get_many(selected_ids)
42+
print(f"\nRetrieved {len(selected_products)} specific products")
43+
44+
# Bulk delete
45+
to_delete = rowids[:20]
46+
deleted_count = client.delete_many(to_delete)
47+
print(f"\nDeleted {deleted_count} products")
48+
print(f"Remaining products: {client.count()}")
49+
50+
client.close()
51+
52+
53+
if __name__ == "__main__":
54+
main()

examples/context_manager.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""Context manager example for sqlite-vec-client.
2+
3+
Demonstrates:
4+
- Using client as context manager
5+
- Automatic connection cleanup
6+
- Exception handling
7+
"""
8+
9+
from sqlite_vec_client import SQLiteVecClient
10+
11+
12+
def main():
13+
# Using context manager - connection closes automatically
14+
with SQLiteVecClient(table="notes", db_path=":memory:") as client:
15+
client.create_table(dim=256, distance="cosine")
16+
17+
texts = ["First note", "Second note", "Third note"]
18+
embeddings = [[0.1] * 256, [0.2] * 256, [0.3] * 256]
19+
20+
rowids = client.add(texts=texts, embeddings=embeddings)
21+
print(f"Added {len(rowids)} notes")
22+
23+
# Search
24+
results = client.similarity_search(embedding=[0.15] * 256, top_k=2)
25+
print("\nTop 2 similar notes:")
26+
for rowid, text, distance in results:
27+
print(f" [{rowid}] {text} (distance: {distance:.4f})")
28+
29+
# Connection is automatically closed here
30+
print("\nConnection closed automatically")
31+
32+
# Exception handling with context manager
33+
try:
34+
with SQLiteVecClient(table="temp", db_path=":memory:") as client:
35+
client.create_table(dim=128, distance="cosine")
36+
# Simulate error
37+
raise ValueError("Simulated error")
38+
except ValueError as e:
39+
print(f"\nHandled error: {e}")
40+
print("Connection still closed properly despite exception")
41+
42+
43+
if __name__ == "__main__":
44+
main()

examples/metadata_filtering.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""Metadata filtering example for sqlite-vec-client.
2+
3+
Demonstrates:
4+
- Adding records with metadata
5+
- Filtering by metadata
6+
- Filtering by text
7+
- Updating metadata
8+
"""
9+
10+
from sqlite_vec_client import SQLiteVecClient
11+
12+
13+
def main():
14+
client = SQLiteVecClient(table="articles", db_path=":memory:")
15+
client.create_table(dim=128, distance="cosine")
16+
17+
# Add articles with metadata
18+
texts = [
19+
"Introduction to Python programming",
20+
"Advanced machine learning techniques",
21+
"Python for data science",
22+
]
23+
24+
embeddings = [
25+
[0.1] * 128,
26+
[0.2] * 128,
27+
[0.15] * 128,
28+
]
29+
30+
metadata = [
31+
{"category": "programming", "author": "Alice", "year": 2023},
32+
{"category": "ai", "author": "Bob", "year": 2024},
33+
{"category": "data-science", "author": "Alice", "year": 2024},
34+
]
35+
36+
rowids = client.add(texts=texts, embeddings=embeddings, metadata=metadata)
37+
print(f"Added {len(rowids)} articles")
38+
39+
# Filter by exact metadata match
40+
alice_articles = client.get_by_metadata(
41+
{"category": "programming", "author": "Alice", "year": 2023}
42+
)
43+
print(f"\nAlice's programming articles: {len(alice_articles)}")
44+
for rowid, text, meta, _ in alice_articles:
45+
print(f" [{rowid}] {text} - {meta}")
46+
47+
# Filter by text
48+
python_articles = client.get_by_text("Python for data science")
49+
print(f"\nPython articles: {len(python_articles)}")
50+
51+
# Update metadata
52+
if rowids:
53+
client.update(
54+
rowids[0],
55+
metadata={
56+
"category": "programming",
57+
"author": "Alice",
58+
"year": 2024,
59+
"updated": True,
60+
},
61+
)
62+
updated = client.get_by_id(rowids[0])
63+
if updated:
64+
print(f"\nUpdated metadata: {updated[2]}")
65+
66+
client.close()
67+
68+
69+
if __name__ == "__main__":
70+
main()

examples/persistent_database.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Persistent database example for sqlite-vec-client.
2+
3+
Demonstrates:
4+
- Creating a persistent .db file
5+
- Loading from existing .db file
6+
- Data persistence across sessions
7+
"""
8+
9+
from sqlite_vec_client import SQLiteVecClient
10+
11+
12+
def create_database():
13+
"""Create and populate a persistent database."""
14+
print("Creating database...")
15+
client = SQLiteVecClient(table="documents", db_path="./my_vectors.db")
16+
client.create_table(dim=128, distance="cosine")
17+
18+
texts = [
19+
"First document",
20+
"Second document",
21+
"Third document",
22+
]
23+
embeddings = [[0.1] * 128, [0.2] * 128, [0.3] * 128]
24+
25+
rowids = client.add(texts=texts, embeddings=embeddings)
26+
print(f"Added {len(rowids)} documents")
27+
print(f"Total records: {client.count()}")
28+
29+
client.close()
30+
31+
32+
def load_database():
33+
"""Load and query existing database."""
34+
print("\nLoading existing database...")
35+
client = SQLiteVecClient(table="documents", db_path="./my_vectors.db")
36+
37+
print(f"Total records: {client.count()}")
38+
39+
# Search
40+
results = client.similarity_search(embedding=[0.15] * 128, top_k=2)
41+
print("\nTop 2 results:")
42+
for rowid, text, distance in results:
43+
print(f" [{rowid}] {text} (distance: {distance:.4f})")
44+
45+
client.close()
46+
47+
48+
if __name__ == "__main__":
49+
create_database()
50+
load_database()

0 commit comments

Comments
 (0)