2016-03-02 40 views
4

我一直在嘗試使用下面的代碼通過java把數據彈性搜索:彈性搜索不是氧化物含量異常

String url = "http://localhost:9200/testindex2/test/2"; 
    HttpClient client = new DefaultHttpClient(); 

    HttpPut put = new HttpPut(url); 
    JSONObject json = new JSONObject(); 

    json.put("email", "[email protected]"); 
    json.put("first_name", "abc"); 
    StringEntity se = new StringEntity("JSON: " + json.toString()); 
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"Text")); 
    put.setEntity(se); 

    HttpResponse response = client.execute(put); 
    System.out.println("\nSending 'PUT' request to URL : " + url); 
    System.out.println("Put parameters : " + put.getEntity()); 
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); 

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

    StringBuffer result = new StringBuffer(); 
    String line = ""; 
    while ((line = rd.readLine()) != null) { 
     result.append(line); 
    } 

    System.out.println(result.toString()); 

而且我收到以下錯誤:

Sending 'PUT' request to URL : http://localhost:9200/testindex2/test/2 Put parameters : [Content-Type: text/plain; charset=ISO-8859-1,Content- Encoding: Text,Content-Length: 52,Chunked: false] Response Code : 400 {"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}},"status":400}

此外,當我嘗試從其餘客戶端運行相同的代碼,它運行得很好,不知道爲什麼會出現這個問題。

回答

3

替換

StringEntity se = new StringEntity("JSON: " + json.toString()); 
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"Text")); 

與此:

StringEntity se = new StringEntity(json.toString(),ContentType.APPLICATION_JSON); 

,現在它的工作

+0

當碰到elasticsearch/logstash API時,其他語言也是如此。當使用通用的http客戶端時,確保在POST請求中將'content-type'設置爲'application/json'。 – tedder42

0

彈性搜索有特殊client與Java一起使用。你不需要手動生成JSON。此外,你沒有描述導入部分,所以有點難以理解你使用的庫。

+0

我不想使用elasticsearch Java客戶端,因爲它連接到端口和elasticsearch HTTP端口是9200所以想單獨進行操作。 –