引入依赖
<dependency>
<groupId>io.milvus</groupId>
<artifactId>milvus-sdk-java</artifactId>
<version>2.4.1</version>
</dependency>
配置milvus客户端
import io.milvus.client.MilvusServiceClient;
import io.milvus.param.ConnectParam;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* milvus配置
* @author tianluhua
* @version 1.0
* @since 2024/8/16 10:15
*/
@Configuration
@ConfigurationProperties(prefix = "milvus.config")
@Data
public class MilvusConfig {
private String host;
private Integer port;
private String database;
@Bean
public MilvusServiceClient getMilvusClient() {
ConnectParam connectParam = ConnectParam.newBuilder()
.withHost(host)
.withPort(port)
.withDatabaseName(database)
.build();
return new MilvusServiceClient(connectParam);
}
}
查询数据
- 查询使用
SearchParam
来构建查询参数。其中
withCollectionName
:查询的集合withVectorFieldName
:向量比对的字段withOutFields
:输出的字段名withFloatVectors
:查询的向量。值为2层数组,即可根据多个特征向量查询。查询结果分别返回多个特征向量的结果withTopK
:返回前x条数据withMetricType
:计算相似度方式
- L2: 欧几里得计算
- COSINE: 余弦相似度计算
List<List<Float>> text_features = vectorizationResponse.getText_features();
SearchParam searchParam = SearchParam.newBuilder()
.withCollectionName(COLLECTION_NAME)
.withVectorFieldName("embedding")
.withOutFields("test")
.withFloatVectors(text_features)
.withMetricType(MetricType.L2)
.withTopK(top)
.build();
R<SearchResults> searchResults = milvusServiceClient.search(searchParam);
SearchResults searchResultsData = searchResults.getData();
SearchResultsWrapper wrapper = new SearchResultsWrapper(searchResultsData.getResults());
List<TextSearchImgResponse> textSearchImgResponses = new ArrayList<>();
for (int i = 0; i < text_features.size(); ++i) {
List<SearchResultsWrapper.IDScore> scores = wrapper.getIDScore(i);
if (scores.size() > 0) {
for (SearchResultsWrapper.IDScore idScore : scores) {
float score = idScore.getScore();
Object imagePathO = idScore.getFieldValues().get(SEARCH_RIELD_NAME);
if (imagePathO != null) {
String relativePath = (imagePathO + "").replace("/cephfs2/data", "")
.replace("/cephfs2/data", "");
String imagePath = filePath + relativePath;
textSearchImgResponses.add(new TextSearchImgResponse(score, imagePath));
}
}
}
}
标签:java,String,new,查询,import,操作,milvus,features
From: https://www.cnblogs.com/knxhd/p/18366620