最近在做一个项目的ES版本升级,从2.4升级至5.2版。由于升级版本跨度比较大,一些Java api都已经废弃了。原来的api,SearchRequestBuilder支持setSource()参数为json格式的字符串。
(1)ES2.4 SearchRequestBuilder setSource方法
public SearchRequestBuilder setSource(String source) {
request.source(source);
return this;
}
(2)ES5.2 SearchRequestBuilder setSource方法
public SearchRequestBuilder setSource(SearchSourceBuilder source) {
request.source(source);
return this;
}
因此,将String json类型转换为SearchSourceBuilder类型,方法如下。
String str = "ES2.4的json";
Settings settings = Settings.builder().build();
SearchModule searchModule = new SearchModule(settings, true, new ArrayList<>());
NamedXContentRegistry xContentRegistry = new NamedXContentRegistry(Stream.of( searchModule.getNamedXContents().stream()).flatMap(Function.identity()).collect(toList()));
XContentType xContentType = XContentType.JSON();
XContentParser xContentParser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY,str);
QueryParseContext queryParseContext = new QueryParseContext(xContentParser);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.parseXContent(queryParseContext);