ElasticSearch學習(2)-Java接口操做ElasticSearch

新建項目:java

pom.xml文件引入依賴json

<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

java鏈接ElasticSearch:

private static final String host = "192.168.15.38";
    private static final int port = 9300;
    private static TransportClient client = null;

    public static TransportClient cilentFactory() {
        client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new TransportAddress(new InetSocketAddress(host, port)));
        return client;
    }

    public static void close() {
        if (client != null) {
            client.close();
        }
    }

建立索引而且插入文檔數據

IndexResponse response = client.prepareIndex("user", "basic_info","1").setSource(jsonObject.toString(), XContentType.JSON).get();
       
        System.out.println("索引:" + response.getIndex());
        System.out.println("類型:" + response.getType());
        System.out.println("id:" + response.getId());
        System.out.println("狀態" + response.status());

獲取文檔

GetResponse response1 = client.prepareGet("user", "basic_info","1").get();
        System.out.println(response1.getSourceAsString());

修改文檔

JsonObject jsonObject2 = new JsonObject();

        jsonObject2.addProperty("name", "張三1");
        jsonObject2.addProperty("age", 21);
        jsonObject2.addProperty("address", "山東威海1");
        jsonObject2.addProperty("email", "zhagnsan_smile@163.com1");
        //修改文檔
        UpdateResponse updateResponse = client.prepareUpdate("user", "basic_info","1").setDoc(jsonObject2.toString(),XContentType.JSON).get();

        System.out.println(updateResponse.getId());

刪除文檔

DeleteResponse deleteResponse = client.prepareDelete("user", "basic_info","1").get();
        System.out.println(deleteResponse.status());
相關文章
相關標籤/搜索