java - 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"}}}}'
有什么线索吗?
解决方案
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);
推荐阅读
- json - 如何从公共 Trello 看板获取信息
- c# - 尝试将 C# 转换为 C++ 时出现问题
- spring-boot - 如何解决 React 中的错误请求错误 400?
- node.js - 我想在swift(IOS)中使用socket.io向特定客户端发送消息?
- matlab - 有没有办法使用 fft 过滤 rgb 图像中的噪声并返回彩色图像作为 matlab 中的输出
- scala - 获取部分列表的列表
- ios - Web 开发:在浏览器中模拟 iphone
- c# - 试图在另一个 GameObjects 本地位置上设置一些东西?
- java - 使 x0 和 y0 从 jframe 的中心开始?
- algorithm - 使用左/右括号序列化和反序列化树