TransportClient 基础CRUD

插入数据时,可以自定义路由routing
参考:https://blog.csdn.net/jatpen/article/details/102632745

    /**
     * 简单查询es 指定index type id
     */
    @Test
    public void search() throws UnknownHostException {
        //获取client
        Settings settings= Settings.builder().put("cluster.name","myes").build();
        TransportClient client=new PreBuiltTransportClient(settings);
        client.addTransportAddress(
                new TransportAddress(InetAddress.getByName("localhost"),9300));
        // 发起请求得到响应
        GetResponse  response=client.prepareGet("index1","type1","6")
            //指定自定义路由routing1
                .setRouting("routing1").get();
    }

    /**
     * 增加文档
     */
    @Test
    public void insert() throws Exception{
        Settings settings= Settings.builder().put("cluster.name","myes").build();
        TransportClient client=new PreBuiltTransportClient(settings);
        client.addTransportAddress(
                new TransportAddress(InetAddress.getByName("localhost"),9300));
        XContentBuilder contentBuilder= XContentFactory.jsonBuilder()
                .startObject()
                .field("author","cchilei")
                .field("id","8")
                .field("title","插入id=8")
                .endObject();
        IndexResponse indexResponse = client.prepareIndex("index1", "type1")
                .setSource(contentBuilder)
                .get();
    }

    /**
     * 删除文档
     */
    @Test
    public void delete() throws Exception{
        Settings settings=Settings.builder().put("cluster.name","myes").build();
        TransportClient client=new PreBuiltTransportClient(settings);
        client.addTransportAddress(
                new TransportAddress(InetAddress.getByName("localhost"),9300));
        DeleteResponse deleteResponse = client
                .prepareDelete("index1", "type1", "8").get();
    }

    /**
     * 修改文档
     */
    @Test
    public void update() throws Exception {
        Settings settings = Settings.builder().put("cluster.name", "myes").build();
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(
                new TransportAddress(InetAddress.getByName("localhost"), 9300));

        UpdateRequest request = new UpdateRequest();
        XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "6868")
                .endObject();
        request.index("index1")
                .type("type1")
                .id("6")
                .doc(contentBuilder);
        UpdateResponse updateResponse = client.update(request).get();
    }
posted @ 2020-09-04 11:28  cchilei  阅读(310)  评论(0编辑  收藏  举报