Springboot使用Milvus的基本操作

发布于:2025-03-01 ⋅ 阅读:(11) ⋅ 点赞:(0)

Milvus

先得保证数据的正确安装并且正确运行

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>
<dependency>
    <groupId>io.milvus</groupId>
    <artifactId>milvus-sdk-java</artifactId>
    <version>2.5.3</version>
</dependency>

代码

// 创建连接参数
ConnectParam connectParam = ConnectParam.newBuilder()
        .withUri("http://192.168.108.191:19530")  // 设置Milvus服务器的URI地址
        .withToken("root:Milvus")                 // 设置访问令牌,格式为 "username:password"
        .withDatabaseName("default")              // 设置要连接的数据库名称
        .build();

// 创建Milvus客户端实例
MilvusServiceClient milvusServiceClient = new MilvusServiceClient(connectParam);

// 创建查询参数
QuerySimpleParam builder = QuerySimpleParam.newBuilder()
        .withCollectionName("test2")              // 设置要查询的集合名称
        .withFilter("f == '7OFT3rsSzZVUtsS'")    // 设置过滤条件,这里查询字段f等于特定字符串的记录
        .withLimit(100L)                          // 设置返回结果的最大数量
        .withOffset(0L)                           // 设置从第几条记录开始返回
        .build();

// 执行查询操作
R<QueryResponse> query = milvusServiceClient.query(builder);

// 获取查询结果
QueryResponse data = query.getData();

// 使用Gson将查询结果转换为JSON格式
Gson gson = new Gson();
System.out.println('1');
System.out.println(gson.toJson(data));           // 打印JSON格式的查询结果

// 关闭客户端连接
milvusServiceClient.close();