Spring Boot和Elasticsearch进行人脸数据的高效检索
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class FaceSearchService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public Page<Face> searchFaces(float[] vector, String collectionId, int page, int size) {
// 构建向量查询
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.scriptScoreQuery(
QueryBuilders.matchAllQuery(),
new ScoreScript.Builder("mscore", ScoreScript.DEFAULT_CONTEXT)
.lang("painless")
.param("vector", vector)
.build()
));
// 设置分页参数
int from = PageRequest.of(page, size).getOffset();
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
// 执行搜索
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id"}, null));
queryBuilder.withQuery(searchSourceBuilder.query());
queryBuilder.withSort(new FieldSortBuilder("_score").order(SortOrder.DESC));
queryBuilder.withPageable(PageRequest.of(page, size));
// 执行搜索并转换结果
Page<SearchHit<Face>> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Face.class, IndexCoordinates.of(collectionId));
List<Face> faces = searchHits.stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
return new PageImpl<>(faces, PageRequest.of(page, size), searchHits.getTotalElements());
}
}
这段代码展示了如何在Spring Boot应用中使用ElasticsearchRestTemplate来执行基于向量相似度的人脸数据搜索。其中Face
类应该包含一个id
属性,以便于之后的查询。ScoreScript
是假设已经定义在Elasticsearch中的一个脚本,用于计算查询向量和文档向量之间的相似度分数。这个
评论已关闭