如何将旧版Elasticsearch Terms查询代码转换为新版TermsQuery.Builder?
转换为新版elasticsearch-java客户端的实现方案
如何传递List类型的ids参数
新版TermsQuery.Builder通过terms().value()方法接收参数,只需将List<String>转换为List<FieldValue>即可(FieldValue是新版客户端用于字段值的封装类),用流式转换就能快速完成适配。
完整转换代码
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.SearchResponse; import co.elastic.clients.elasticsearch.core.search.FetchSourceFilter; import co.elastic.clients.elasticsearch.core.search.Hit; import co.elastic.clients.elasticsearch._types.FieldValue; import co.elastic.clients.elasticsearch._types.query_dsl.Query; import co.elastic.clients.elasticsearch._types.query_dsl.TermsQuery; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; // 已初始化的ElasticsearchClient实例 ElasticsearchClient esClient; List<String> ids; Pageable pageable; // 构建Terms查询 TermsQuery idsQuery = new TermsQuery.Builder() .field("id") .terms(t -> t.value( ids.stream() .map(FieldValue::of) .collect(Collectors.toList()) )) .build(); // 封装为顶层Query对象 Query query = Query.of(q -> q.terms(idsQuery)); // 构建源过滤器(对应旧版FetchSourceFilterBuilder) FetchSourceFilter sourceFilter = new FetchSourceFilter.Builder().build(); // 如需指定包含/排除字段,可添加:.includes("字段1", "字段2").excludes("敏感字段") // 构建并执行搜索请求 SearchResponse<Profile> searchResponse = esClient.search( s -> s.index("你的索引名称") // 新版需显式指定索引 .query(query) .fetchSource(f -> f.filter(sourceFilter)) .from((int) pageable.getOffset()) .size(pageable.getPageSize()), Profile.class ); // 处理结果 List<Profile> profiles = searchResponse.hits().hits().stream() .map(Hit::source) .collect(Collectors.toList());
关键差异说明
- 参数转换:旧版直接传
List<String>,新版需要转成List<FieldValue>,用FieldValue::of完成类型适配。 - 索引指定:新版客户端要求显式声明查询的索引,旧版可能通过模板或配置默认设置。
- 分页处理:用
from(偏移量)和size(每页数量)替代旧版的Pageable直接传入,通过pageable.getOffset()和pageable.getPageSize()转换。 - 结果处理:新版用
SearchResponse接收结果,通过hits().hits()获取命中列表,再提取source得到实体对象。
内容的提问来源于stack exchange,提问作者user352290
相关产品推荐
相关产品推荐

