如何检查elasticsearch中的存在数据并插入或更新新数据

时间:2017-04-22 11:00:31

标签: java elasticsearch

我的elasticsearch正在使用2.4版。 我的java编码如下:

 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);
    }
}

我当前的编码只使用json将数据插入到elasticsearch中。 插入后如下: [enter image description here] [1

如何使用java编码检查来自elasticsearch的存在数据,如果只存在则更新新数据,如果不存在,则插入到elasticsearch中。

例如: 当新数据进入,并在弹性搜索的TAG中检查id时,一旦从字段标签获得id,它只更新字段stkno。

请提出建议,如果可以,请提供样本java编码参考。

由于

1 个答案:

答案 0 :(得分:0)

您可以使用Elasticsearch的更新API(示例here)并将文档ID与有效内容一起传递以更新内容。

假设文档具有唯一ID,您可以执行以下操作:

UpdateRequest updateRequest = new UpdateRequest();
updateRequest.docAsUpsert(true);
updateRequest.index(index);
updateRequest.type(type);
updateRequest.id(id);
updateRequest.doc(json);

UpdateResponse response = client.update(updateRequest).actionGet();
if (response.isCreated()) {
//Created a new document
}else{
//Updated an existing document
}