forked from KnowledgeXLab/LeanRAG
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqdrant_manager.py
More file actions
530 lines (448 loc) · 21.2 KB
/
qdrant_manager.py
File metadata and controls
530 lines (448 loc) · 21.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
519
520
521
522
523
524
525
526
527
528
529
530
#!/usr/bin/env python3
"""
Qdrant Collection Management Utility
====================================
Manage Qdrant collections: delete, recreate, check status
Works exclusively with the official Qdrant Python SDK.
"""
import sys
import os
import argparse
import json
from typing import Optional, List, Dict, Any
from pathlib import Path
# Load .env from repo root if present
try:
from dotenv import load_dotenv
ROOT = Path(__file__).parent.parent
dotenv_path = ROOT / '.env'
load_dotenv(dotenv_path)
except ImportError:
print("Warning: python-dotenv not installed. Install with: pip install python-dotenv")
# Official Qdrant Python SDK - required dependency
try:
from qdrant_client import QdrantClient
from qdrant_client.http import models
from qdrant_client.http.models import Distance, VectorParams, CollectionInfo
from qdrant_client.http.exceptions import UnexpectedResponse
except ImportError as e:
print(f"Error: Qdrant Python SDK not installed. Install with: pip install qdrant-client")
print(f"Import error: {e}")
sys.exit(1)
# Configuration from environment
QDRANT_URL = os.getenv('QDRANT_URL', 'http://localhost:6333')
QDRANT_API_KEY = os.getenv('QDRANT_API_KEY')
DEFAULT_COLLECTION = os.getenv('QDRANT_COLLECTION', 'history')
class QdrantManager:
"""
Comprehensive Qdrant collection management using the official Python SDK.
Features:
- Collection CRUD operations
- Point management (add, delete, search)
- Storage inspection and statistics
- Health monitoring
- Batch operations
"""
def __init__(self, collection_name: str = DEFAULT_COLLECTION, default_vector_size: int = 1536):
self.collection_name = collection_name
self.default_vector_size = default_vector_size
self.client = self._create_client()
def _create_client(self) -> QdrantClient:
"""Create and configure the Qdrant client"""
try:
if QDRANT_API_KEY:
client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
else:
client = QdrantClient(url=QDRANT_URL)
# Test connection
client.get_collections()
return client
except Exception as e:
raise RuntimeError(f'Failed to connect to Qdrant at {QDRANT_URL}: {e}')
def health_check(self) -> bool:
"""Check if Qdrant is reachable and responsive"""
try:
collections = self.client.get_collections()
return True
except Exception as e:
print(f"Health check failed: {e}")
return False
def get_cluster_info(self) -> Dict[str, Any]:
"""Get comprehensive cluster information"""
try:
info = {
'url': QDRANT_URL,
'collections': [],
'total_points': 0,
'total_collections': 0,
'cluster_info': None
}
# Get all collections
collections_response = self.client.get_collections()
collections = collections_response.collections
info['total_collections'] = len(collections)
# Get detailed info for each collection
for collection in collections:
try:
collection_info = self.client.get_collection(collection.name)
points_count = collection_info.points_count or 0
info['total_points'] += points_count
# Extract vector configuration
vectors_config = collection_info.config.params.vectors
if isinstance(vectors_config, dict):
# Named vectors
vector_info = {name: {'size': vec.size, 'distance': vec.distance.value}
for name, vec in vectors_config.items()}
else:
# Single vector
vector_info = {'default': {'size': vectors_config.size, 'distance': vectors_config.distance.value}}
info['collections'].append({
'name': collection.name,
'points_count': points_count,
'vectors': vector_info,
'status': collection_info.status.value if collection_info.status else 'unknown'
})
except Exception as e:
info['collections'].append({
'name': collection.name,
'error': str(e)
})
# Try to get cluster info (if available)
try:
cluster_info = self.client.get_cluster_info()
info['cluster_info'] = {
'peer_id': cluster_info.peer_id,
'peers': len(cluster_info.peers) if cluster_info.peers else 1
}
except:
pass # Cluster info not available in single-node setups
return info
except Exception as e:
return {'error': str(e)}
def list_collections(self) -> None:
"""List all collections with detailed information"""
info = self.get_cluster_info()
if 'error' in info:
print(f"❌ Error getting cluster info: {info['error']}")
return
print(f"📊 Qdrant Cluster Status")
print(f"URL: {info['url']}")
print(f"Collections: {info['total_collections']}")
print(f"Total Points: {info['total_points']:,}")
if info['cluster_info']:
print(f"Cluster: {info['cluster_info']['peers']} peer(s)")
print("-" * 60)
if info['total_collections'] == 0:
print("No collections found")
return
for col in info['collections']:
if 'error' in col:
print(f" 📁 {col['name']} (❌ Error: {col['error']})")
continue
print(f" 📁 {col['name']}")
print(f" Status: {col['status']}")
print(f" Points: {col['points_count']:,}")
# Display vector configurations
for vec_name, vec_config in col['vectors'].items():
name_suffix = f" ({vec_name})" if vec_name != 'default' else ""
print(f" Vector{name_suffix}: {vec_config['size']}D, {vec_config['distance']}")
# Show sample points if collection has data
if col['points_count'] > 0:
self._show_sample_points(col['name'], limit=2)
print()
def _show_sample_points(self, collection_name: str, limit: int = 3) -> None:
"""Show sample points from a collection"""
try:
# Use scroll to get points without needing a query vector
points, _ = self.client.scroll(collection_name=collection_name, limit=limit)
if points:
print(f" 📝 Sample points:")
for i, point in enumerate(points, 1):
# Extract meaningful text from payload
text = ""
if point.payload:
# Common text fields
text = (point.payload.get('text') or
point.payload.get('content') or
point.payload.get('message') or
str(point.payload))
# Truncate text for display
if isinstance(text, str) and len(text) > 100:
text = text[:97] + "..."
print(f" {i}. ID: {point.id}")
if text:
print(f" Text: {text}")
if point.payload and len(point.payload) > 1:
keys = [k for k in point.payload.keys() if k not in ['text', 'content', 'message']]
if keys:
print(f" Fields: {', '.join(keys[:5])}")
except Exception as e:
print(f" ⚠️ Could not fetch sample points: {e}")
def collection_info(self) -> None:
"""Show detailed information about the specific collection"""
try:
collection_info = self.client.get_collection(self.collection_name)
print(f"📊 Collection: {self.collection_name}")
print("-" * 50)
print(f"Status: {collection_info.status.value}")
print(f"Points: {collection_info.points_count:,}")
# Vector configuration
vectors_config = collection_info.config.params.vectors
if isinstance(vectors_config, dict):
print("Vector configurations:")
for name, config in vectors_config.items():
print(f" {name}: {config.size}D, {config.distance.value}")
else:
print(f"Vector size: {vectors_config.size}D")
print(f"Distance metric: {vectors_config.distance.value}")
# Indexing configuration
if collection_info.config.hnsw_config:
hnsw = collection_info.config.hnsw_config
print(f"HNSW M: {hnsw.m}, EF Construct: {hnsw.ef_construct}")
# Show sample search if there are points
if collection_info.points_count > 0:
print("\n🔍 Sample search (random vector):")
self._perform_sample_search()
except UnexpectedResponse as e:
if e.status_code == 404:
print(f"❌ Collection '{self.collection_name}' does not exist")
else:
print(f"❌ Error getting collection info: {e}")
except Exception as e:
print(f"❌ Error getting collection info: {e}")
def _perform_sample_search(self) -> None:
"""Perform a sample search with a random vector"""
try:
import random
# Create a random vector for search
query_vector = [random.random() for _ in range(self.default_vector_size)]
results = self.client.search(
collection_name=self.collection_name,
query_vector=query_vector,
limit=3
)
for i, result in enumerate(results, 1):
text = ""
if result.payload:
text = (result.payload.get('text') or
result.payload.get('content') or
result.payload.get('message') or
str(result.payload))
if isinstance(text, str) and len(text) > 80:
text = text[:77] + "..."
print(f" {i}. Score: {result.score:.3f}, ID: {result.id}")
if text:
print(f" Text: {text}")
except Exception as e:
print(f" ⚠️ Sample search failed: {e}")
def delete_collection(self, force: bool = False) -> bool:
"""Delete the collection"""
try:
# Check if collection exists
try:
collection_info = self.client.get_collection(self.collection_name)
points_count = collection_info.points_count
except UnexpectedResponse as e:
if e.status_code == 404:
print(f"ℹ️ Collection '{self.collection_name}' does not exist")
return True
raise
if not force:
print(f"⚠️ About to delete collection '{self.collection_name}'")
print(f" This will permanently remove {points_count:,} points")
confirm = input(" Are you sure? (y/N): ").strip().lower()
if confirm != 'y':
print("❌ Deletion cancelled")
return False
self.client.delete_collection(collection_name=self.collection_name)
print(f"✅ Deleted collection '{self.collection_name}' ({points_count:,} points)")
return True
except Exception as e:
print(f"❌ Error deleting collection: {e}")
return False
def create_collection(self, vector_size: Optional[int] = None,
distance: str = 'Cosine',
hnsw_m: int = 16,
hnsw_ef_construct: int = 100) -> bool:
"""Create a new collection with specified parameters"""
try:
vsize = vector_size or self.default_vector_size
# Convert distance string to enum
distance_enum = getattr(Distance, distance.upper(), Distance.COSINE)
vectors_config = VectorParams(
size=vsize,
distance=distance_enum
)
# HNSW configuration for better performance
hnsw_config = models.HnswConfigDiff(
m=hnsw_m,
ef_construct=hnsw_ef_construct
)
self.client.create_collection(
collection_name=self.collection_name,
vectors_config=vectors_config,
hnsw_config=hnsw_config
)
print(f"✅ Created collection '{self.collection_name}'")
print(f" Vector size: {vsize}D")
print(f" Distance: {distance}")
print(f" HNSW M: {hnsw_m}, EF Construct: {hnsw_ef_construct}")
return True
except Exception as e:
print(f"❌ Error creating collection: {e}")
return False
def recreate_collection(self, vector_size: Optional[int] = None, **kwargs) -> bool:
"""Delete and recreate the collection"""
print(f"🔄 Recreating collection '{self.collection_name}'")
if self.delete_collection(force=True):
return self.create_collection(vector_size=vector_size, **kwargs)
return False
def add_point(self, point_id: str, vector: List[float],
payload: Optional[Dict[str, Any]] = None) -> bool:
"""Add a single point to the collection"""
try:
self.client.upsert(
collection_name=self.collection_name,
points=[models.PointStruct(
id=point_id,
vector=vector,
payload=payload or {}
)]
)
print(f"✅ Added point {point_id}")
return True
except Exception as e:
print(f"❌ Error adding point: {e}")
return False
def delete_point(self, point_id: str) -> bool:
"""Delete a single point from the collection"""
try:
self.client.delete(
collection_name=self.collection_name,
points_selector=models.PointIdsList(points=[point_id])
)
print(f"✅ Deleted point {point_id}")
return True
except Exception as e:
print(f"❌ Error deleting point: {e}")
return False
def search_points(self, query_vector: List[float], limit: int = 10,
score_threshold: Optional[float] = None) -> List[models.ScoredPoint]:
"""Search for similar points"""
try:
return self.client.search(
collection_name=self.collection_name,
query_vector=query_vector,
limit=limit,
score_threshold=score_threshold
)
except Exception as e:
print(f"❌ Error searching points: {e}")
return []
def get_storage_info(self) -> None:
"""Display storage and configuration information"""
print("💾 Qdrant Storage Information")
print("-" * 50)
print(f"Connection URL: {QDRANT_URL}")
print(f"API Key: {'Set' if QDRANT_API_KEY else 'Not set'}")
print(f"Target Collection: {self.collection_name}")
print()
# Cluster info
cluster_info = self.get_cluster_info()
if 'error' not in cluster_info:
print(f"Total Collections: {cluster_info['total_collections']}")
print(f"Total Points: {cluster_info['total_points']:,}")
if cluster_info['cluster_info']:
print(f"Cluster Peers: {cluster_info['cluster_info']['peers']}")
print("\n🗑️ Management Options:")
print(" 1. List all collections: --list")
print(" 2. Collection details: --info")
print(" 3. Delete collection: --delete")
print(" 4. Recreate collection: --recreate")
print(" 5. Health check: --health")
def main():
parser = argparse.ArgumentParser(
description='Qdrant Collection Management - Official Python SDK',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python qdrant_manager.py --list # List all collections
python qdrant_manager.py --info # Show collection details
python qdrant_manager.py --health # Health check
python qdrant_manager.py --delete --force # Delete without confirmation
python qdrant_manager.py --recreate --vector-size 768 # Recreate with different size
python qdrant_manager.py --add-point --id "test1" --vector "0.1,0.2,0.3" --payload '{"text":"test"}'
""")
parser.add_argument('--collection', type=str, default=DEFAULT_COLLECTION,
help=f'Collection name (default: {DEFAULT_COLLECTION})')
parser.add_argument('--list', action='store_true', help='List all collections')
parser.add_argument('--info', action='store_true', help='Show collection information')
parser.add_argument('--delete', action='store_true', help='Delete the collection')
parser.add_argument('--recreate', action='store_true', help='Delete and recreate collection')
parser.add_argument('--storage', action='store_true', help='Show storage information')
parser.add_argument('--health', action='store_true', help='Run health check')
parser.add_argument('--force', action='store_true', help='Force operations without confirmation')
# Collection creation options
parser.add_argument('--vector-size', type=int, help='Vector size for new collections')
parser.add_argument('--distance', choices=['Cosine', 'Euclidean', 'Dot'], default='Cosine',
help='Distance metric for vectors')
parser.add_argument('--hnsw-m', type=int, default=16, help='HNSW M parameter')
parser.add_argument('--hnsw-ef-construct', type=int, default=100, help='HNSW EF construct parameter')
# Point operations
parser.add_argument('--add-point', action='store_true', help='Add a point to the collection')
parser.add_argument('--delete-point', action='store_true', help='Delete a point from the collection')
parser.add_argument('--id', type=str, help='Point ID for add/delete operations')
parser.add_argument('--vector', type=str, help='Comma-separated vector values')
parser.add_argument('--payload', type=str, help='JSON payload for the point')
args = parser.parse_args()
# Default to showing help if no operation specified
operations = [args.list, args.info, args.delete, args.recreate, args.storage,
args.health, args.add_point, args.delete_point]
if not any(operations):
parser.print_help()
return
try:
manager = QdrantManager(collection_name=args.collection)
except RuntimeError as e:
print(f"❌ {e}")
return
# Execute requested operations
if args.health:
ok = manager.health_check()
print('✅ Qdrant is reachable and responsive' if ok else '❌ Qdrant is not reachable')
if args.list:
manager.list_collections()
if args.info:
manager.collection_info()
if args.storage:
manager.get_storage_info()
if args.delete:
manager.delete_collection(force=args.force)
if args.recreate:
kwargs = {}
if args.distance:
kwargs['distance'] = args.distance
if args.hnsw_m:
kwargs['hnsw_m'] = args.hnsw_m
if args.hnsw_ef_construct:
kwargs['hnsw_ef_construct'] = args.hnsw_ef_construct
manager.recreate_collection(vector_size=args.vector_size, **kwargs)
if args.add_point:
if not args.id or not args.vector:
print('❌ Error: --id and --vector are required for --add-point')
return
try:
vector = [float(x.strip()) for x in args.vector.split(',') if x.strip()]
payload = None
if args.payload:
payload = json.loads(args.payload)
manager.add_point(args.id, vector, payload)
except (ValueError, json.JSONDecodeError) as e:
print(f'❌ Error parsing vector or payload: {e}')
if args.delete_point:
if not args.id:
print('❌ Error: --id is required for --delete-point')
return
manager.delete_point(args.id)
if __name__ == "__main__":
main()