Milvus笔记

Milvus版本 2.3.5

    <dependency>
      <groupId>io.milvus</groupId>
      <artifactId>milvus-sdk-java</artifactId>
      <version>2.3.4</version> 还没有2.3.5依赖
        <!--      <scope>provided</scope>-->
    </dependency>

一、创建操作

1、python版本

from pymilvus import Collection, FieldSchema, DataType, CollectionSchema, connections
from pymilvus.orm import utility, db

from knowledge_brain.milvus_sink import milvus_sink
from study.connect import Connect

class MilvusOperatC:

    def __init__(self, host, port, user, password, db_name ,alias,collection_name,schema,num_shards): #,collection_name,schema,shards_num
        print("加载milvus依赖")
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db_name = db_name
        self.alias = alias
        self.collection_name = collection_name
        self.schema = schema
        self.num_shards = num_shards
        self.collection = self.con()

    #创建连接
    """
    host  ip
    port  端口
    user  用户名
    password 密码
    db_name 数据库
    alias 别名
    """

    def con(self):
        connections.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            port=self.port,
            alias=self.alias)
        # 是否有该数据库,无则新建
        print("建立数据库连接~~~~")
        if self.db_name in db.list_database():
            pass
        else:
            print("没有%s数据库,进行新建~~~~" % self.db_name)
            db.create_database(self.db_name)
            print("新建%s数据库完成!" % self.db_name)
        # 使用数据库,建立数据库连接
        db.using_database(self.db_name)
        # 是否有该集合,无则创建
        if utility.has_collection(self.collection_name):
            print("集合已存在")
            pass
        else:
            print("没有%s集合,进行新建~~~~" % self.collection_name)
            self.col_create()
            print("新建%s集合完成!" % self.collection_name)
        collection = Collection(self.collection_name)
        print("数据库连接完成!")
        return collection

    #集合创建
    """
    collection_name 集合名称
    schema   表头描述信息
    database  数据库信息
    shards_num 分片信息
    """

    def col_create(self):
        # fields = [
        #     FieldSchema(name='vec', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024),
        #     FieldSchema(name='doc_slicing_id', dtype=DataType.VARCHAR, descrition='doc_slicing_id', max_length=100,
        #                 is_primary=True),
        #     FieldSchema(name='doc_id', dtype=DataType.VARCHAR, descrition='doc_id', max_length=100)
        # ]
        # schema = CollectionSchema(fields=fields, description=self.col_name)
        collection = Collection(name=self.collection_name, schema=self.schema,num_shards=self.num_shards)
        print(collection)

    #索引创建
    def index_create(self,index_params:str,vec_field:str):
        # create IVF_FLAT index for collection.
        # index_params = {
        #     'metric_type': 'L2',
        #     'index_type': "IVF_FLAT",
        #     'params': {"nlist": 150}
        # }
        self.collection.create_index(field_name=vec_field, index_params=index_params)
        # collection.create_index(
        #     field_name="doc_id",
        #     index_name="doc_id_index"
        # )
        # collection.load()

    #分区创建
    def partition_create(self,partition_name:str):
        self.collection.create_partition(partition_name)


    def load(self):
        self.collection.load()
        print("数据load成功")

    def unload(self):
        self.collection.release()


if __name__ == '__main__':
    host='XX.17.38'
    port='31639'
    user='Milvus'
    password='Milvus'
    db_name='knowledge_test'
    alias='default'


    fields = [
        FieldSchema(name='pk', dtype=DataType.INT64, descrition='主键', max_length=200, is_primary=True,
                    auto_id=True),
        FieldSchema(name='car_model', dtype=DataType.VARCHAR, descrition='car_model', max_length=65535, is_primary=False,
                    auto_id=False),
        FieldSchema(name='text', dtype=DataType.VARCHAR, descrition='page_content', max_length=65535, is_primary=False,
                    auto_id=False),
        FieldSchema(name='vector', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024)
    ]
    schema = CollectionSchema(fields=fields, description='集合描述')

    # Collection('test',schema)
    # MilvusCreate(host,port,user,password,db_name,alias,'test',schema,2)

    milvus_sink(db_name,'test',1,1,1)

python调用

from pymilvus import FieldSchema, DataType, CollectionSchema
from study.MilvusOperatC import MilvusOperatC

if __name__ == '__main__':
    host='XXX.17.38'
    port='31639sss'
    user='Milvus'
    password='Milvus'
    db_name='knowledge_test'
    alias='default'
    fields = [
        FieldSchema(name='pk', dtype=DataType.INT64, descrition='主键', max_length=200, is_primary=True,
                    auto_id=True),
        FieldSchema(name='car_model', dtype=DataType.VARCHAR, descrition='car_model', max_length=65535,
                    is_primary=False,
                    auto_id=False),
        FieldSchema(name='text', dtype=DataType.VARCHAR, descrition='page_content', max_length=65535, is_primary=False,
                    auto_id=False),
        FieldSchema(name='vector', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024)
    ]
    schema = CollectionSchema(fields=fields, description='集合描述')
    index_params = {
        'metric_type': 'L2',#COSINE IP
        'index_type': "IVF_FLAT",
        'params': {"nlist": 150}
    }
    #embedding字段名称
    vec_field = "vector"
    mc = MilvusOperatC(host,port,user,password,db_name,alias,'test',schema,2)
    mc.index_create(index_params,vec_field)
    mc.partition_create('2024032103')
    mc.load()
    mc.unload()


search_params = {
        "metric_type": "L2",
        "offset": 0,
        "ignore_growing": False,
        "params": {"nprobe": 10}
    }
    mc1 = MilvusOperatR(host, port, user, password, db_name, alias,'test')
    res = mc1.search(search_params=search_params,embeddings=[[0.5441558957099915,0.9319176077842712]],anns_field='vector',topK=10,expr=None,output_fields=['id','vector'])
    print(res)
    output_fields = ["id"]
    res1 = mc1.query(expr="",offset=0,topK=10,output_fields=output_fields)
    print(res1)
    res2 = mc1.count(expr="",output_fields=["count(*)"])
    print(res2)

2、java版本

package com.XXXX.milvus;

import com.google.gson.internal.$Gson$Preconditions;
import io.milvus.client.MilvusServiceClient;
import io.milvus.grpc.DataType;
import io.milvus.grpc.GetLoadStateResponse;
import io.milvus.grpc.GetLoadingProgressResponse;
import io.milvus.param.*;
import io.milvus.param.collection.*;
import io.milvus.param.index.CreateIndexParam;
import io.milvus.param.partition.CreatePartitionParam;

/**
 * @author yangyingchun
 * @version 1.0
 * @date 2024/3/20 16:02
 */
public class MilvusOperateC {

    /**
     * 获取连接
     * @param host
     * @param port
     * @param username
     * @param password
     * @param database
     * @return
     */
    public static MilvusServiceClient getConn(String host,Integer port,String username,String password,String database){
        MilvusServiceClient milvusServiceClient= new MilvusServiceClient(ConnectParam
                .newBuilder()
                .withHost(host)
                .withPort(port)
                .withAuthorization(userna
<think>好的,我现在需要帮助用户解决在Windows上启动Milvus Lite的问题。根据用户提供的引用内容,我需要综合这些信息来整理出一个清晰的步骤流程。 首先,用户提到引用[1]指出官网上没有明确的Windows安装流程,存在误导信息,甚至很多资料错误地声称Windows无法安装Milvus Lite。因此,正确的步骤可能涉及创建虚拟环境。引用[2]提到需要启用WSL功能,这可能是关键步骤,因为Milvus Lite可能依赖于Linux环境。引用[3]则说明Milvus可以在各种环境包括笔记本电脑上运行,支持开源和云服务形式。 接下来,我需要验证这些步骤是否合理。首先,用户需要在Windows上启用WSL,这是运行Linux环境的前提。然后,安装一个Linux发行版,比如Ubuntu。接着,在WSL中创建Python虚拟环境,安装Milvus Lite的Python包,并通过Python代码启动服务。这可能是因为Milvus Lite作为Python库,需要通过Python环境运行,而WSL提供了必要的Linux支持。 需要注意用户可能不熟悉WSL的使用,所以步骤需要详细说明如何启用WSL,安装Ubuntu,以及基本的命令行操作。此外,安装Python和pip,创建虚拟环境,安装Milvus Lite的包,这些步骤都需要逐一解释。最后,提供一个简单的Python脚本示例来启动Milvus Lite服务,并验证是否成功。 可能的问题点包括:是否正确启用了WSL,是否成功安装了Ubuntu,Python环境是否正确配置,以及Milvus Lite的版本兼容性。需要提醒用户检查这些步骤,并确保网络连接正常,避免安装包时出现问题。此外,用户可能需要了解基本的Linux命令和Python虚拟环境的使用方法,如果用户不熟悉,可能需要进一步指导或提供参考资料。 总结下来,步骤应该是:启用WSL → 安装Ubuntu → 更新系统 → 安装Python和pip → 创建虚拟环境 → 安装Milvus Lite → 编写启动脚本 → 运行并验证。同时,需要指出这些方法并非官方明确支持,但通过社区验证可行,用户需注意潜在问题。</think>在Windows操作系统上启动Milvus Lite的步骤如下(基于社区验证方法整理): ### 步骤1:启用WSL功能 1. 以管理员身份打开PowerShell 2. 执行命令: ```powershell dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart ``` 3. 重启系统完成WSL安装[^2] ### 步骤2:安装Linux发行版 1. 从Microsoft Store安装Ubuntu 20.04 LTS 2. 启动Ubuntu并完成初始配置 ### 步骤3:准备Python环境 ```bash sudo apt update && sudo apt upgrade -y sudo apt install python3-pip -y python3 -m venv milvus-env source milvus-env/bin/activate ``` ### 步骤4:安装Milvus Lite ```bash pip install milvus ``` ### 步骤5:启动服务 创建Python脚本`start_milvus.py`: ```python from milvus import default_server with default_server: default_server.start() input("按Enter停止服务...") default_server.stop() ``` 执行脚本: ```bash python3 start_milvus.py ``` ### 验证连接 ```python from milvus import connections connections.connect("default", host="127.0.0.1", port=default_server.listen_port) print(connections.get_connection_addr("default")) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值