connections_test.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # connections_test_final_last.py(终极适配版,无任何导入错误)
  2. from pymilvus import connections, CollectionSchema, FieldSchema, DataType, Collection
  3. from pymilvus.orm import use_database, list_collections
  4. MILVUS_HOST = "192.168.92.61"
  5. MILVUS_PORT = 19530
  6. TARGET_DB = "lq_db" # 旧数据可能存在的数据库
  7. VECTOR_DIM = 128 # 替换为你的向量维度(比如 768)
  8. try:
  9. # 1. 建立连接
  10. connections.connect(
  11. alias="milvus_last_conn",
  12. host=MILVUS_HOST,
  13. port=MILVUS_PORT,
  14. timeout=30
  15. )
  16. print("✅ Milvus 连接成功!")
  17. # 2. 尝试切换到 lq_db 数据库
  18. print(f"🔄 尝试切换到数据库:{TARGET_DB}")
  19. use_database(TARGET_DB, using="milvus_last_conn")
  20. print(f"✅ 成功切换到数据库:{TARGET_DB}")
  21. # 3. 查询 lq_db 中所有 Collection(自动找旧数据)
  22. print(f"\n📋 {TARGET_DB} 数据库中所有 Collection:")
  23. all_collections = list_collections(using="milvus_last_conn")
  24. if not all_collections:
  25. print(f"❌ {TARGET_DB} 中无任何 Collection(旧数据元数据已丢失)")
  26. else:
  27. print(f"✅ 找到 {len(all_collections)} 个 Collection:{all_collections}")
  28. # 4. 遍历每个 Collection 查数据量
  29. for coll_name in all_collections:
  30. print(f"\n=== 🔍 Collection:{coll_name} ===")
  31. # 定义通用结构(适配大多数场景)
  32. fields = [
  33. FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
  34. FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
  35. ]
  36. schema = CollectionSchema(fields=fields)
  37. coll = Collection(
  38. name=coll_name,
  39. schema=schema,
  40. using="milvus_last_conn"
  41. )
  42. row_count = coll.num_entities
  43. if row_count > 0:
  44. print(f"🎉 旧数据找到!数据量:{row_count} 条")
  45. print(f"👉 Attu 切换到 {TARGET_DB} → 选择 {coll_name} 即可查看!")
  46. else:
  47. print(f"⚠️ 该 Collection 无数据")
  48. except Exception as e:
  49. error_msg = str(e).lower()
  50. if "database not found" in error_msg:
  51. print(f"❌ 未找到 {TARGET_DB} 数据库(旧数据库已丢失)")
  52. else:
  53. print(f"❌ 错误:{e}")
  54. finally:
  55. # 断开连接
  56. if connections.has_connection("milvus_last_conn"):
  57. connections.disconnect("milvus_last_conn")
  58. print("\n🔌 已断开连接")
  59. if __name__ == "__main__":
  60. pass