Docker 教程十三 JAVA 操作elasticsearch

feri發表於2018-08-07

第一步:依賴 jar

 <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.10</version>
        </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());

相關文章