-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_usage.py
More file actions
151 lines (133 loc) · 4.87 KB
/
basic_usage.py
File metadata and controls
151 lines (133 loc) · 4.87 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
import os
from dotenv import load_dotenv
from ricedb import RiceDBClient
import time
load_dotenv()
HOST = os.environ.get("HOST", "localhost")
PORT = int(os.environ.get("PORT", "50051"))
PASSWORD = os.environ.get("PASSWORD", "admin")
SSL = os.environ.get("SSL", "false").lower() == "true"
def main():
# Initialize client (auto-selects transport)
client = RiceDBClient(HOST, port=PORT)
client.ssl = SSL
# Connect to the server
print("Connecting to RiceDB server...")
try:
if client.connect():
transport_info = client.get_transport_info()
print(f" Connected via {transport_info['type'].upper()}")
# Login as admin (default credentials)
print(" Logging in...")
client.login("admin", PASSWORD)
print(" Logged in successfully")
else:
print(" Failed to connect to RiceDB server")
print(" Make sure the server is running:")
print(" - HTTP: cargo run --example http_server --features http-server")
print(" - gRPC: cargo run --bin ricedb-server-grpc --features grpc-server")
return
except Exception as e:
print(f" Connection/Login error: {e}")
return
# Check server health
print("\nChecking server health...")
try:
health = client.health()
print(f" Server status: {health.get('status', 'Unknown')}")
print(f" Version: {health.get('version', 'Unknown')}")
except Exception as e:
print(f" Health check failed: {e}")
return
# Prepare test data
print("\nPreparing test data...")
user_id = 100
documents = [
{
"id": 1,
"text": "Q4 Budget Report - Financial analysis of quarterly expenses and revenue.",
"metadata": {
"title": "Q4 Budget Report",
"department": "Finance",
"type": "report",
},
},
{
"id": 2,
"text": "Team collaboration guidelines for engineering department. Includes code review process.",
"metadata": {
"title": "Team Wiki",
"department": "Engineering",
"type": "documentation",
},
},
{
"id": 3,
"text": "Project technical requirements specification for the new mobile app.",
"metadata": {
"title": "Project Specification",
"department": "Engineering",
"type": "specification",
},
},
{
"id": 4,
"text": "Alice likes peanuts and goes to the park.",
"metadata": {"title": "Story 1"},
},
{
"id": 5,
"text": "Bob is allergic to peanuts and stays home.",
"metadata": {"title": "Story 2"},
},
]
print(f" Prepared {len(documents)} documents")
# Insert documents
print("\nInserting documents (HDC Encoding)...")
start_time = time.time()
try:
for doc in documents:
result = client.insert(
node_id=doc["id"],
text=doc["text"],
metadata=doc["metadata"],
user_id=user_id,
)
if result.get("success", True):
print(f" Inserted: {doc['metadata']['title']} (ID: {doc['id']})")
else:
print(f" Failed to insert: {doc['metadata']['title']}")
except Exception as e:
print(f" Insert error: {e}")
return
print(f" Insertion took {time.time() - start_time:.4f}s")
# Search for documents
print("\nSearching documents (HDC Resonance)...")
queries = [
("financial analysis", "Search for financial documents"),
("code review process", "Search for engineering guidelines"),
("Alice peanuts", "Search for Alice story"),
("mobile app requirements", "Search for project specs"),
]
for query_text, description in queries:
print(f"\n {description}:")
print(f" Query: '{query_text}'")
try:
start_search = time.time()
# client.search now takes text directly
results = client.search(query_text, user_id=user_id, k=3)
duration = time.time() - start_search
print(f" Found {len(results)} results in {duration:.4f}s:")
for i, result in enumerate(results, 1):
title = result["metadata"].get("title", "Unknown")
similarity = result.get("similarity", 0)
print(f" {i}. {title} - Score: {similarity:.4f}")
except Exception as e:
print(f" Search error: {e}")
# Cleanup
print("\nCleanup...")
client.disconnect()
print(" Disconnected from server")
print("\nExample completed successfully!")
if __name__ == "__main__":
main()