2017-09-14 54 views
0

我們正在開發一個彈性搜索應用程序在春季啓動。我們不能使用彈性搜索提供的Java API或Java Rest Client API。相反,我們需要使用彈簧休息模板進行彈性操作,但彈性似乎不接受來自其他客戶端的索引請求。我們得到「不可接受」響應。我真的很感激,如果有人給我們一些提示或信息。如何實現Spring Rest客戶端進行彈性搜索?

彈性版本:5.6

+1

請顯示您現在的密碼。而對於ES 5.6,您可以使用[低級別REST客戶端](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low-usage-initialization。 html),它只是Apache HTTP客戶端的一個包裝,沒有任何其他的依賴關係。 – Val

+0

很可能你沒有在你的HTTP請求頭中發送Content-Type頭。可能? – Val

回答

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(); 
+0

你能舉一個簡單的請求體進行搜索嗎? – Vikki

+1

更新了我的答案。希望有所幫助。 –

相關問題