0
我的elasticsearch使用的是版本2.4。 我的Java編碼如下:使用JSON如何在elasticsearch中檢查現有數據並插入或更新新數據
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public void generateJsonObject(NewsContentObj newsContentObj, String sNewsID) {
try {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
if (sExDate.equalsIgnoreCase("1900-01-01")) {
sExDate = "";
}
if (sPaymnetDate.equalsIgnoreCase("1900-01-01")) {
sPaymnetDate = "";
}
newsContentObj.setExDate(sExDate);
newsContentObj.setPaymentDate(sPaymnetDate);
String Json = gson.toJson(newsContentObj);
out.println("ElasticSearch sNewsID :" + sNewsID);
out.println("JSON :" + Json);
sendIndexer(sNewsID, Json);
} catch (Exception ex) {
out.println("News Id :" + sNewsID + " -> Exception :" + ex);
ex.printStackTrace();
}
}
// Sharon 20161011 elastic search
private void sendIndexer(String nid, String json) {
try {
String url = indexserver + nid;
StringEntity reqEntity = new StringEntity(json, "application/json", "UTF8");
HttpPost post = new HttpPost(url);
post.setEntity(reqEntity);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse res = httpclient.execute(post);
// Issue to solve: if sleep is not applied,
// JQC will be too quick to respond and call back ES causing blank data as ES had not finish index new data
// below is just temp fix, most likely need migrate to use ES API to get actual push index success
// Thread.sleep(5000);
// Debug purpose
// out.println("Send Indexer status: " + res.getStatusLine());
} catch (UnsupportedEncodingException uee) {
out.println("Send Indexer encoding exception: This should not happen unless hardcoded item being changed!");
} catch (ClientProtocolException cpe) {
out.println("Send Indexer CPE exception: " + cpe);
} catch (IOException ioe) {
out.println("Send Indexer IO exception: " + ioe);
}
}
我目前唯一的編碼中插入數據elasticsearch。 插入之後將是如下: [] [1
如何用Java編碼來檢查從elasticsearch存在數據,如果存在僅更新新的數據,如果沒有存在,插入elasticsearch。
例如: 當新數據進入時,並且在elasticsearch的TAG處檢查id,一旦它從field標記中獲得id,它只會更新字段stkno。
敬請建議,如果正常,得到了樣品Java代碼來指代。
感謝
意味着我需要使用5.3 elasticsearch正好可以利用這個編碼?如何檢查現有數據? –
您不需要爲此使用elasticsearch 5.3,更新API適用於任何版本(嘗試從RHS drodown中選擇不同的版本)。就檢查現有數據而言,上述代碼通過'id'進行檢查。如果你想檢查其他字段,請查看[this](https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-update)。 html#java-docs-update-api-upsert)的例子。 –
我需要使用什麼jar文件? –