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

标签 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 效果很好

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"}}}}'

有什么线索吗?

最佳答案

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);

关于java - RestTemplate 到 elasticsearch 6.7.0 搜索 -> 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56791210/

相关文章:

java - 享元设计模式

java - 使用 JFileChooser 选择文件

spring-boot - 在Spring Cloud Config中,curl客户端如何工作?

java - @ConditionalOnProperty 用于多值属性

elasticsearch - elasticsearch与neo4j数据库的集成

java - 如何从 Avg Aggregation Builder elasticsearch 获取特定键的平均值

java - 如何在 Spring Boot wicket 应用程序中注入(inject) RequestScope bean

java - Tomcat集群中如何维护应用范围?

spring - Intellij IDEA 提示无法解决 Spring Boot 属性,但它们工作正常

elasticsearch - minimum_master_nodes = 2,有 3 个符合资格的主节点 -> 如果只有一个节点在线,那么什么都不会起作用