1. 程式人生 > >elasticsearch的java api基本操作

elasticsearch的java api基本操作

1.新增依賴

預設elasticsearch的配置已經沒有問題了,本文使用elasticsearch版本為6.4.2,依賴如下:

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.4.2</version>
        </dependency>

2.使用transport連線elasticsearch叢集

①、公用方法
    private static TransportClient getClient() throws Exception {
        // client.transport.sniff=true :使客戶端嗅探整個叢集狀態,把叢集中其他機器的ip地址新增到客戶端中
        Settings settings = Settings.builder().put("cluster.name", "my-es-cluster")
                .put("client.transport.sniff", true).build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("10.49.2.18"), 9300));
        return client;
    }

    private static XContentBuilder getJsonBuilder() throws Exception {
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
        return jsonBuilder;
    }
②、建立索引
    private static void createDoc() throws Exception {
        TransportClient client = TestES2.getClient();
        XContentBuilder source = new XContentFactory().jsonBuilder()
                .startObject()
                .startObject("settings") //設定文件屬性
                .field("number_of_shards", 1)
                .field("number_of_replicas", 0)
                .endObject()
                .endObject()
                .startObject()
                .startObject("testlog") // 文件型別
                .startObject("properties")
                .startObject("type")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .startObject("eventCount")
                .field("type", "long")
                .field("store", "yes")
                .endObject()
                .startObject("eventDate")
                .field("type", "date")
                .field("format", "dateOptionalTime")
                .field("store", "yes")
                .endObject()
                .startObject("message")
                .field("type", "string")
                .field("index", "not_analyzed")
                .field("store", "yes")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        CreateIndexRequestBuilder cirb = client.admin().indices().prepareCreate("testhello")
                .setSource(source);
        CreateIndexResponse response = cirb.execute().actionGet();
        if (response.isAcknowledged()) {
            System.out.println("index create success!");
        } else {
            System.out.println("index create failed!");
        }
    }
③、新增文件
    private static void addDoc() throws Exception {
        TransportClient client = TestES2.getClient();
        XContentBuilder jsonBuilder = TestES2.getJsonBuilder();
        IndexResponse response = client.prepareIndex("testhello", "testlog", "1")
                .setSource(jsonBuilder.startObject()
                        .field("type", "log")
                        .field("eventCount", 1)
                        .field("eventDate", new Date())
                        .field("message", "testlog insert doc test")
                        .endObject()
                ).get();
        System.out.println("index:" + response.getIndex() + " insert doc id:" + response.getId() + " result:" + response.getResult());
    }
④、更新文件
    private static void updateDoc() throws Exception {
        UpdateRequest request = new UpdateRequest();
        request.index("testhello");
        request.type("testlog");
        request.id("1");
        XContentBuilder jsonBuilder = TestES2.getJsonBuilder();
        request.doc(jsonBuilder.startObject().field("type", "file").endObject());
        UpdateResponse response = TestES2.getClient().update(request).get();
        System.out.println("result:" + response.getResult()); // result:UPDATED
    }
⑤、查詢文件
    private static void searchDoc() throws Exception {
        TransportClient client = TestES2.getClient();
        // 索引 型別 文件id
        GetResponse response = client.prepareGet("testhello", "testlog", "1").get();
        System.out.println(response);
    }
⑥、刪除文件
    private static void deleteDoc() throws Exception {
        TransportClient client = TestES2.getClient();
        DeleteResponse deleteResponse = client.prepareDelete("testhello", "testlog", "1").get();
        // 判斷是否能夠刪除
        System.out.println(deleteResponse.status());
        // testhello為索引名稱
        DeleteIndexRequest request = new DeleteIndexRequest("testhello");
        ActionFuture<DeleteIndexResponse> actionFuture = client.admin().indices().delete(request);
        DeleteIndexResponse response = actionFuture.actionGet();
        // response.isAcknowledged()若為true則刪除成功
        if (response.isAcknowledged()) {
            System.out.println("刪除成功!");
        } else {
            System.out.println("刪除失敗!");
        }
    }