Docker 教程十三 JAVA 操作elasticsearch

第一步:依赖 jar

 
        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>transportartifactId>
            <version>5.6.10version>
        dependency>

第二步:新增索引

 public final static String HOST = "10.211.55.33";
    public final static int PORT = 9300;//http请求的端口是9200,客户端是9300
    private static  TransportClient client;

    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder().put("cluster.name", "es01").build();
        //创建客户端
        client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));

        IndexResponse response = client.prepareIndex("books", "book", "2")
                .setSource(jsonBuilder().
                        startObject()
                        .field("book_name", "ElasticSearch入门")
                        .field("author", "老邢")
                        .field("publish_time", new Date())
                        .endObject())
                .get();
        //关闭客户端
        client.close();
    }

第四步:获取索引

  public final static String HOST = "10.211.55.33";
    public final static int PORT = 9300;//http请求的端口是9200,客户端是9300
    private static  TransportClient client;

    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder().put("cluster.name", "es01").build();
        //创建客户端
        client = new PreBuiltTransportClient(settings).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));
        GetResponse getResponse = client.prepareGet("books", "book", "2").get();
        System.err.println("索引库的数据:" + getResponse.getSourceAsString());
        //关闭客户端
        client.close();
        }

第五步:修改索引

  //修改
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("author","feri");
        UpdateResponse updateResponse = client.prepareUpdate("books", "book", "2")
                .setDoc(jsonObject.toString(),XContentType.JSON).get();

第六步:删除索引

 DeleteResponse deleteResponse = client.prepareDelete("books", "book", "1").get();

        System.err.println("deleteResponse索引名称:" + deleteResponse.getIndex() + "\n deleteResponse类型:" + deleteResponse.getType()
                + "\n deleteResponse文档ID:" + deleteResponse.getId() + "\n当前实例deleteResponse状态:" + deleteResponse.status());

你可能感兴趣的:(ElasticSearch,Docker)