How to set the query via JSON to an Elasticsearch SearchRequest?
I'm now generating the SearchSourceBuilder this way:
String query = "..."
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
try (XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(new NamedXContentRegistry(searchModule
.getNamedXContents()), query)) {
searchSourceBuilder.parseXContent(parser);
}
I too was facing the same issue. We had been updating from ES 1.4.4 to ES 6.4.2 and I had used Java High Level Rest Client provided by ES to do create/update/delete operations in ES. I couldn't find an easy way to convert a query JSON used in prev ES version to an appropriate searchRequest using the High Level Rest Client. The below is what I ended up using.
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.Request;
public static Response executeGetRequest(RestHighLevelClient client,
String api, String body) throws Exception {
Request request = new Request("GET", api);
if(body != null && !body.isEmpty()) {
request.setJsonEntity(body);
}
Response response = client.getLowLevelClient()
.performRequest(request);
if (response == null) {
throw new Exception(
"Get request have failed");
}
return response;
}