Java客戶端實現ElasticSearch編程 -- (二)創建索引庫

使用Java客戶端創建索引庫

步驟

(1)創建一個Java工程。

(2)添加jar包,添加maven座標。

(3)編寫測試方法實現創建索引庫。

  • 創建一個Settings對象,相當於是一個配置信息。主要配置集羣的名稱。

  • 創建一個客戶端Client對象。

  • 使用client對象創建一個索引庫。

  • 關閉client對象。

 

代碼:

package com.itdemo.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;

public class ElasticSearchClientTest {
/*
    實現創建索引庫步驟:
        1.創建一個Settings對象,相當於是一個配置信息。主要配置集羣的名稱。
        2.創建一個客戶端Client對象。
        3.使用client對象創建一個索引庫。
        4.關閉client對象。
 */

    @Test
    public void createIndex() throws Exception {
        // 1.創建一個Settings對象
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();

        // 2.創建一個客戶端Client對象
        TransportClient client = new PreBuiltTransportClient(settings);
        // 指定集羣中節點的列表
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));

        // 3.使用client對象創建一個索引庫,索引庫名稱爲index_hello(前面爲設置,get()爲執行操作)
        client.admin().indices().prepareCreate("index_hello").get();

        // 關閉client對象
        client.close();
    }

}

實現效果:

(1)執行單元測試,執行成功:

(2)觀察效果:

執行前:

執行後:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章