python使用milvus向量库
milvus向量库使用的时候需要先本地安装使用windows安装milvus需要使用docker使用管理员身份打开powershell执行Invoke-WebRequest https://raw.githubusercontent.com/milvus-io/milvus/refs/heads/master/scripts/standalone_embed.bat -OutFile standalone.bat生成好文件standalone.bat继续执行.\standalone.bat start当看到类似Start successfully.的提示就表示启动成功了。输入docker ps就可以看见milvus-standalone进程其中python代码里连接方式如下client MilvusClient(urihttp://localhost:19530, tokenroot:Milvus )其中如果报错(base) PS D:\ .\standalone.bat startError response from daemon: Ports are not available: exposing port TCP 0.0.0.0:2379 - 127.0.0.1:0: listen tcp 0.0.0.0:2379: bind: An attempt was made to access a socket in a way forbidden by its access permissions.Error: failed to start containers: milvus-standaloneStart failed.重启电脑即可使用docker安装miluvus之后启动就比较快了日志如下启动 2026-04-25 16:44:31启动结束 2026-04-25 16:44:31加载模型 2026-04-25 16:44:31后面加载模型时候一直报错embed_model SentenceTransformer(all-MiniLM-L6-v2)报错内容(MaxRetryError(HTTPSConnectionPool(hosthuggingface.co, port443): Max retries exceeded with url: /sentence-transformers/all-MiniLM-L6-v2/resolve/main/modules.json (Caused by ConnectTimeoutError(HTTPSConnection(hosthuggingface.co, port443) at 0x2043accaab0, Connection to huggingface.co timed out. (connect timeout10)))), (Request ID: c314c2ba-9ac0-4790-905a-96832e0122c9)) thrown while requesting HEAD https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/./modules.jsonRetrying in 1s [Retry 1/5].这个是因为网络原因需要使用外网或者加上os.environ[HF_ENDPOINT] https://hf-mirror.com表示连接的是国内镜像源在对向量库进行增删改查的时候需要先创建集合类似mysql里的表def create_collection_if_not_exists(): print(创建collection) if client.has_collection(COLLECTION_NAME): return schema client.create_schema(auto_idTrue) schema.add_field(field_nameid,datatypeDataType.INT64, is_primaryTrue) schema.add_field(field_namemodule, datatypeDataType.VARCHAR, max_length1000) schema.add_field(field_namesection, datatypeDataType.VARCHAR, max_length200) schema.add_field(field_namecontent, datatypeDataType.VARCHAR, max_length65535) schema.add_field(field_namevector, datatypeDataType.FLOAT_VECTOR, dim384) # 创建索引必须创建 index_params client.prepare_index_params() index_params.add_index( field_namevector, metric_typeCOSINE, index_typeIVF_FLAT, params{nlist: 128}) # 这里是重点 client.create_collection( collection_nameCOLLECTION_NAME, schemaschema, index_paramsindex_params ) print(集合创建成功)另外浏览器端访问milvus的方式docker run -d -p 8082:3000 \-e MILVUS_URLhost.docker.internal:19530 \zilliz/attu:latest使用浏览器访问localhost:8082