有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java RestTemplate到elasticsearch 6.7.0搜索>错误请求

我正在尝试访问elasticsearch 6.7.0

(我不能使用elasticsearch rest高级客户端,因为我已经使用了7.1.0版,我正在使用不同版本的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) 个答案

  1. # 1 楼答案

    ^{} 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);