Java客戶端實現ElasticSearch編程 -- (三)設置mappings

使用Java客戶端設置Mappings

步驟

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

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

  • 使用client對象創建一個mapping信息(json數據,可以是字符串,也可以是XContextBuilder對象)。

  • 使用client向es服務器發送mappings信息。

  • 關閉client對象。

 

【案例】初始時index_hello的mappings爲空,我們要對此索引的mappings進行設置。

(1)編寫代碼:

    @Test
    public void setMappings() 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對象創建一個mapping信息
        // 創建一個mappings信息
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder
                .startObject()  // 左邊的花括號
                    .startObject("article")
                        .startObject("properties")
                            .startObject("id")
                                .field("type", "long")
                                .field("store", true)
                            .endObject()
                            .startObject("title")
                                .field("type", "text")
                                .field("store", true)
                                .field("analyzer", "ik_smart")
                            .endObject()
                            .startObject("content")
                                .field("type", "text")
                                .field("store", true)
                                .field("analyzer", "ik_smart")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();

        // 4.使用client向es服務器發送mapping信息
        client.admin().indices()
                .preparePutMapping("index_hello")   // 設置要做映射的索引
                .setType("article")     // 設置要做映射的type
                .setSource(builder)     // mapping信息,可以是XContentBuilder對象,也可以是json格式的字符串
                .get();         // 執行操作

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

    }

 

(2)執行成功:

 

(3)觀察數據,發現成功設置了mappings:

 

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