【问题标题】:How to implement Spring Rest Client for elastic search?如何为弹性搜索实现 Spring Rest Client?
【发布时间】:2017-09-14 23:12:24
【问题描述】:

我们正在 Spring Boot 中开发一个弹性搜索应用程序。我们不能使用弹性搜索提供的 Java API 或 Java Rest Client API。相反,我们需要使用 spring rest 模板在 elastic 中进行操作,但 elastic 似乎不接受来自 rest 客户端的索引请求。我们得到了“不可接受”的响应。如果有人给我们一些提示或信息,我真的很感激。

弹性版本:5.6

【问题讨论】:

  • 请出示您现在拥有的代码。在 ES 5.6 中,您可以使用 low-level REST client,它只是 Apache 的 HTTP 客户端的包装器,没有任何其他依赖项。
  • 很可能您没有在 HTTP 请求标头中发送 Content-Type 标头。可能吗?

标签: elasticsearch spring-boot spring-data-elasticsearch


【解决方案1】:

试试这个。它适用于我使用 HttpURLConnection 通过 HTTP API 索引文档。

URL obj = new URL("http://localhost:9200/index/type");
String json = "{\n" + 
            "    \"user\" : \"kimchy\",\n" + 
            "    \"post_date\" : \"2009-11-15T14:12:12\",\n" + 
            "    \"message\" : \"trying out Elasticsearch\"\n" + 
            "}";
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.write(json);
osw.flush();
osw.close();

System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
if (con != null)
    con.disconnect();

使用 HttpURLConnection 进行简单搜索。

URL obj = new URL("http://localhost:9200/index/type/_search");
String json = "{\n" + 
                "  \"query\": {\n" + 
                "    \"match_all\": {}\n" + 
                "  }\n" + 
                "}";
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.write(json);
osw.flush();
osw.close();

BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));

System.out.println("Response : " + br.readLine());

System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());

if (con != null)
    con.disconnect();

【讨论】:

  • 你能展示一个使用简单请求正文进行搜索的示例吗?
  • 更新了我的答案。希望对您有所帮助。
猜你喜欢
  • 2017-10-19
  • 2018-06-08
  • 2017-04-29
  • 2019-11-21
  • 1970-01-01
  • 2014-11-04
  • 2021-02-02
  • 2023-04-10
  • 2017-10-30
相关资源
最近更新 更多