引入依賴
<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));
}
}
}
}