elasticsearch更新数据

来源:互联网 发布:linux网络关闭启动命令 编辑:程序博客网 时间:2024/05/16 09:27

private static TransportClient client=EsClient.getTransportClient();

1、更新方法(一)

   public static void upMethod1(String index,String type,HashMap<String, String> map) {
        try {
            // 方法一:创建一个UpdateRequest,然后将其发送给client.
            UpdateRequest uRequest = new UpdateRequest();
            uRequest.index(index);
            uRequest.type(type);
            uRequest.id(map.get("id"));
            uRequest.doc(XContentFactory.jsonBuilder().startObject().field("content", "学习目标 掌握java泛型的产生意义ssss").endObject());
            client.update(uRequest).get();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

2、更新方法(二)

     
    public static void updateDoc(String index,String type,HashMap<String, Object> map) {
        // 方法三:prepareUpdate() 使用doc更新索引
        try {
            client.prepareUpdate(index, type, map.get("id").toString()).setDoc(XContentFactory.jsonBuilder().startObject().field("title", "测试是是是是").endObject()).get();
        } catch (Exception e) {
            client.close();
            e.printStackTrace();
        }

    }

3、更新方法(三)

     public static void updateRequest(String index,String type,HashMap<String, Object> map) {
        // 方法四: 增加新的字段
        try {
            XContentBuilder c=XContentFactory.jsonBuilder().startObject();
            for(String key:map.keySet()){
                c.field(key, map.get(key).toString());    //便利map,多行更新
            }
            c.endObject();
            UpdateRequest updateRequest = new UpdateRequest(index, type, map.get("id").toString())
                    .doc(c);
            client.update(updateRequest).get();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

4、更新方法(四)

         public static void upMethod4() {
        // 方法五:upsert 如果文档不存在则创建新的索引
        try {
            IndexRequest indexRequest = new IndexRequest("blog", "article", "10").source(XContentFactory.jsonBuilder().startObject()
                    .field("title", "Git安装10").field("content", "学习目标 git。。。10").endObject());

            UpdateRequest uRequest2 = new UpdateRequest("blog", "article", "10").doc(XContentFactory.jsonBuilder().startObject().field("title", "Git安装").field("content", "学习目标 git。。。").endObject())
                    .upsert(indexRequest);
            client.update(uRequest2).get();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

0 0
原创粉丝点击