首页 > 解决方案 > RestTemplate 到 elasticsearch 6.7.0 搜索 -> 错误请求

问题描述

我试图访问 elasticsearch 6.7.0

(我不能使用elasticsearch-rest-high-level-client,因为我已经使用了7.1.0版本,我正在使用不同版本的2个elasticsearch)

所以我用 RestTemplate 构建它

但我收到 400 错误

 {"error":
   {"root_cause": 
 [{"type":"parse_exception","reason":"request body or source     parameter is  required"}],
 "type":"parse_exception","reason":"request body or source parameter     is required"},
"status":400}
}

这是我试过的

protected void findByRest(String identification) throws Exception {
        RestTemplate restTemplate = new RestTemplate();

        String url = "http://127.0.0.1:9200/_search/template";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);


        String json = "{\"source\":{\"size\":\"2000\",\"query\":{\"match\":{\"identification\":\"123456789\"}}}}";

        HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);

        try {
            ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Object.class);
        }catch (HttpClientErrorException e) {
            LOG.error("{}",e.getResponseBodyAsString());
            throw w;
        }
    }

卷曲效果很好

curl -X GET \
  http://127.0.0.1:9200/_search/template \
  -H 'Accept: */*' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Host: 127.0.0.1:9200' \
  -H 'Postman-Token: 7d1e98f4-23ba-437b-95a7-ea8df9fac837,079e18f5-aaee-4b19-802b-ef4337eaf8c5' \
  -H 'User-Agent: PostmanRuntime/7.15.0' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'cache-control: no-cache' \
  -H 'content-length: 80' \
  -d '{"source":{"size":"2000","query":{"match":{"identificacion":"132465789"}}}}'

有什么线索吗?

标签: javaspring-bootelasticsearchresttemplate

解决方案


source应该是查询字符串参数,而不是查询 DSL 中的部分。但是您应该能够发送该查询而不在查询字符串中发送它,这无论如何都是一种不好的做法。

我这样做的方式是这样的,而且效果很好(即使用 POST 而不是 GET,因为您正在发送有效负载)

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<String> requestEntity = new HttpEntity(payload.getBytes(Charset.defaultCharset()), headers);
ResponseEntity<String> response = this.restTemplate.postForEntity(url, requestEntity, String.class);

推荐阅读