RestTemplate到elasticsearch 6.7.0搜索->错误的请求

时间:2019-06-27 12:38:23

标签: java spring-boot elasticsearch resttemplate

我尝试访问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"}}}}'

任何线索?

1 个答案:

答案 0 :(得分:0)

source is supposed to be a query string parameter,而不是查询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);