基于Elasticsearch Java API的Kotlin脚本评分搜索实现求助
基于co.elastic.clients的Kotlin实现方案
最新的co.elastic.clients库采用Builder模式构建查询,你之前的代码问题在于混用了旧版API的类结构。以下是完全匹配你提供的Elasticsearch DSL的可行实现:
import co.elastic.clients.elasticsearch._types.ScoreMode import co.elastic.clients.elasticsearch._types.Script import co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreQuery import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery import co.elastic.clients.elasticsearch._types.query_dsl.Query import co.elastic.clients.elasticsearch.search.SearchRequest import co.elastic.clients.json.JsonData fun buildVectorSearchRequest(queryVector: List<Double>, indexName: String = "_all"): SearchRequest { // 构建脚本评分函数 val scriptScore = Script.of { s -> s.source("cosineSimilarity(params.query_vector, 'vector') + 1") .params(mapOf("query_vector" to JsonData.of(queryVector))) } // 构建function_score查询 val functionScoreQuery = FunctionScoreQuery.of { f -> f.query(Query.of { q -> q.matchAll(MatchAllQuery.of { m -> m }) }) .functions { fn -> fn.scriptScore { ss -> ss.script(scriptScore) } } .scoreMode(ScoreMode.Sum) } // 构建最终搜索请求 return SearchRequest.of { r -> r.index(indexName) .query(Query.of { q -> q.functionScore(functionScoreQuery) }) } } // 示例调用 fun main() { val queryVector = listOf(1.2, 3.4, 5.6) // 替换为你的实际向量数据 val searchRequest = buildVectorSearchRequest(queryVector) println(searchRequest.toString()) }
核心要点说明:
- Script构建:使用
Script.of()的Lambda构建器,向量参数必须通过JsonData.of()包装,确保与Elasticsearch的类型系统兼容。 - FunctionScoreQuery构建:通过
FunctionScoreQuery.of()的Lambda,依次指定底层查询(match_all)、添加script_score函数、设置评分模式。 - SearchRequest构建:借助
SearchRequest.of()的Lambda配置索引和查询,所有查询需包装为Query类型。 - 确保依赖最新版客户端库,比如Gradle Kotlin DSL中添加:
implementation("co.elastic.clients:elasticsearch-java:8.13.0") implementation("com.fasterxml.jackson.core:jackson-databind:2.15.2") // 依赖的JSON处理库
内容的提问来源于stack exchange,提问作者developerd
相关产品推荐
相关产品推荐

