milvus向量数据库连接测试 和 集合维度不同搜索不到内容

1.连接测试

复制代码
import random
import time
from pymilvus import (
    connections,
    utility,
    FieldSchema, CollectionSchema, DataType,
    Collection,
)

# 定义测试集合名称和参数
COLLECTION_NAME = "test_collection"
DIMENSION = 128  # 向量维度
INDEX_FILE_SIZE = 32  # 索引文件大小
METRIC_TYPE = "L2"  # 距离度量类型:欧氏距离
INDEX_TYPE = "IVF_FLAT"  # 索引类型
NLIST = 1024  # IVF 索引的聚类数
NPROBE = 16  # 搜索时探测的聚类数
TOP_K = 5  # 搜索返回的最近邻数量

def connect_to_milvus():
    """连接到Milvus服务器"""
    print("连接到 Milvus 服务器...")
    try:
        connections.connect("default", host="localhost", port="19530")
        print("连接成功!")
        return True
    except Exception as e:
        print(f"连接失败: {e}")
        return False

def create_collection():
    """创建集合及其字段"""
    if utility.has_collection(COLLECTION_NAME):
        utility.drop_collection(COLLECTION_NAME)
        print(f"已删除现有集合: {COLLECTION_NAME}")

    # 定义集合字段
    fields = [
        FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=False),
        FieldSchema(name="random_value", dtype=DataType.DOUBLE),
        FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=DIMENSION)
    ]

    # 创建集合模式
    schema = CollectionSchema(fields, description="测试集合")

    # 创建集合
    collection = Collection(name=COLLECTION_NAME, schema=schema)
    print(f"集合 '{COLLECTION_NAME}' 创建成功")
    return collection

def insert_data(collection, num_entities=10):
    """向集合中插入向量数据"""
    # 生成一些随机数据
    entities = [
        # id 字段
        [i for i in range(num_entities)],
        # random_value 字段
        [random.random() for _ in range(num_entities)],
        # embedding 字段 (向量)
        [[random.random() for _ in range(DIMENSION)] for _ in range(num_entities)]
    ]

    # 插入数据
    insert_result = collection.insert(entities)

    # 数据插入后需要刷新集合以确保数据可用于搜索
    collection.flush()
    print(f"成功插入 {insert_result.insert_count} 条记录")

    return insert_result

def create_index(collection):
    """为集合创建索引"""
    # 创建索引
    index_params = {
        "metric_type": METRIC_TYPE,
        "index_type": INDEX_TYPE,
        "params": {"nlist": NLIST}
    }

    print(f"正在为 'embedding' 字段创建 {INDEX_TYPE} 索引...")
    collection.create_index("embedding", index_params)
    print("索引创建成功!")

def perform_search(collection, search_vectors):
    """执行向量搜索"""
    # 加载集合到内存
    collection.load()

    # 设置搜索参数
    search_params = {"metric_type": METRIC_TYPE, "params": {"nprobe": NPROBE}}

    # 执行搜索
    results = collection.search(
        data=search_vectors,      # 要搜索的向量
        anns_field="embedding",   # 要在其上执行搜索的字段
        param=search_params,      # 搜索参数
        limit=TOP_K,              # 返回的最近邻数量
        output_fields=["random_value"]  # 要返回的额外字段
    )

    return results

def main():
    """主测试函数"""
    # 连接到 Milvus 服务器
    if not connect_to_milvus():
        return

    # 创建测试集合
    collection = create_collection()

    # 插入数据
    insert_data(collection, num_entities=100)

    # 创建索引
    create_index(collection)

    # 生成一些搜索向量
    vectors_to_search = [[random.random() for _ in range(DIMENSION)] for _ in range(2)]

    # 执行向量搜索
    results = perform_search(collection, vectors_to_search)

    # 打印搜索结果
    for i, hits in enumerate(results):
        print(f"搜索向量 {i} 的结果:")
        for hit in hits:
            print(f"ID: {hit.id}, 距离: {hit.distance}, 随机值: {hit.entity.get('random_value')}")

    # 清理:删除集合
    if utility.has_collection(COLLECTION_NAME):
        utility.drop_collection(COLLECTION_NAME)
        print(f"测试完成,集合 '{COLLECTION_NAME}' 已删除")

if __name__ == "__main__":
    main()

2.起初的搞的代码是向量维度1024和我的768不匹配,删除再建立解决

3.找不到module问题->添加到系统路径路径

向上两层

复制代码
import sys
# 获取当前文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
#打印出来
print(f"当前目录: {current_dir}")
# 获取上一级目录(父目录)
parent_dir = os.path.dirname(current_dir)
# 打印出来
print(f"父目录: {parent_dir}")
# 获取上两级目录(父目录的父目录)
grandparent_dir = os.path.dirname(parent_dir)
# 打印出来
print(f"上两级目录: {grandparent_dir}")
# 将上两级目录添加到 Python 模块搜索路径中

if grandparent_dir not in sys.path:
    print(f"添加上两级目录到系统路径: {grandparent_dir}")
sys.path.append(grandparent_dir)

向上一层

复制代码
# 添加项目根目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
相关推荐
海天一色y3 天前
生产级医疗AI Agent:Multi-Agent RAG架构解析
redis·milvus·multi-agent
Hrain-AI3 天前
AI 爬虫三档授权工程落地:搜索放行、训练拦截、Agent 分层(附脚本)
人工智能·elasticsearch·milvus
happy_king_zi4 天前
Milvus 生产环境部署,优化,日常维护中遇到的问题
llm·milvus
jason_renyu6 天前
Windows 环境下 Python 方式安装 Milvus 向量库与 Attu 避坑指南
人工智能·milvus·windows安装milvus·windows安转向量库
forestsea7 天前
从零构建 Java 智能体 RAG 系统:Milvus 向量数据库实战指南
java·数据库·milvus
java_logo8 天前
Docker 部署 Milvus:轻松搭建高性能向量数据库平台
数据库·docker·私有化部署·milvus·向量数据库·rag·轩辕镜像
ACGkaka_8 天前
RAG(二):Milvus 下载与安装
milvus
像风一样自由20208 天前
29.Redis在大模型应用中有哪些用途缓存会话与限流
数据库·人工智能·redis·缓存·大模型·milvus·智能体
牛油果子哥q9 天前
向量数据库原理与工程选型:FAISS深度剖析、Milvus基础、检索优化、分片与持久化落地
数据库·milvus·faiss