milvus demo java
时间: 2024-01-25 12:03:45 浏览: 234
Demo.java
以下是一个Milvus的Java示例代码:
```java
import io.milvus.client.*;
import java.util.Arrays;
import java.util.List;
public class MilvusDemo {
public static void main(String[] args) {
// 设置Milvus服务器的IP地址和端口号
String host = "127.0.0.1";
int port = 19530;
// 创建Milvus客户端
MilvusClient client = new MilvusGrpcClient();
// 连接到Milvus服务器
ConnectParam connectParam = new ConnectParam.Builder()
.withHost(host)
.withPort(port)
.build();
Response connectResponse = client.connect(connectParam);
if (!connectResponse.ok()) {
System.out.println("连接到Milvus服务器失败:" + connectResponse.getMessage());
return;
}
// 创建一个Milvus集合
String collectionName = "my_collection";
FieldSchema vectorField = new FieldSchema.Builder("vector", DataType.FLOAT_VECTOR, 128).build();
CollectionMapping collectionMapping = new CollectionMapping.Builder(collectionName, Arrays.asList(vectorField)).build();
Response createCollectionResponse = client.createCollection(collectionMapping);
if (!createCollectionResponse.ok()) {
System.out.println("创建Milvus集合失败:" + createCollectionResponse.getMessage());
return;
}
// 插入向量数据
List<FloatVector> vectors = Arrays.asList(
new FloatVector(Arrays.asList(0.1f, 0.2f, 0.3f)),
new FloatVector(Arrays.asList(0.4f, 0.5f, 0.6f)),
new FloatVector(Arrays.asList(0.7f, 0.8f, 0.9f))
);
InsertParam insertParam = new InsertParam.Builder(collectionName, vectors).build();
Response insertResponse = client.insert(insertParam);
if (!insertResponse.ok()) {
System.out.println("插入向量数据失败:" + insertResponse.getMessage());
return;
}
// 查询相似的向量
List<FloatVector> queryVectors = Arrays.asList(
new FloatVector(Arrays.asList(0.2f, 0.3f, 0.4f))
);
SearchParam searchParam = new SearchParam.Builder(collectionName, queryVectors, 1).build();
Response searchResponse = client.search(searchParam);
if (!searchResponse.ok()) {
System.out.println("查询相似的向量失败:" + searchResponse.getMessage());
return;
}
// 打印查询结果
SearchResult searchResult = searchResponse.getSearchResult();
List<List<SearchResult.VectorData>> vectorDataList = searchResult.getVectorDataList();
for (List<SearchResult.VectorData> vectorData : vectorDataList) {
for (SearchResult.VectorData data : vectorData) {
System.out.println("相似的向量:" + data.getVector());
System.out.println("相似度:" + data.getDistance());
}
}
// 断开与Milvus服务器的连接
Response disconnectResponse = client.disconnect();
if (!disconnectResponse.ok()) {
System.out.println("断开与Milvus服务器的连接失败:" + disconnectResponse.getMessage());
return;
}
}
}
```
阅读全文