Elasticsearch5.3 用JAVA创建索引

                                                                            创建索引
1,首先我们要有已经搭建好的Elasticsearch 并且是没问题的!
废话不多说直接上代码了


import com.google.gson.Gson;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
//import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

/**
 * Created by 启才 on 2017/4/25.
 */
public class BookRepositoryTest {

    TransportClient client;

    @Before
    public void setup() throws UnknownHostException {
        System.out.println("create TransportClient...");
        client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("....."), 9300));
    }

    @After
    public void clearup() {
        System.out.println("close TransportClient...");
        if (client != null) {
            client.close();
        }
    }

    @Test
    public void doIndex() throws IOException {
        Gson gson = new Gson();

        Map map = new HashMap();
        map.put("title", "hello test");
        map.put("description", "你好世界");
        map.put("price", 25.3);
        map.put("onSale", "asdasdasda");
        map.put("type", "testtypesssss");
        map.put("createDate", "2017.0000");


        String json = gson.toJson(map);

        IndexRequestBuilder indexRequestBuilder = client.prepareIndex("wang", "test", "10").setSource(json);
        IndexResponse response = indexRequestBuilder.get();

        // Index name
        String _index = response.getIndex();
// Type name
        String _type = response.getType();
// Document ID (generated or not)
        String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
        long _version = response.getVersion();
// status has stored current instance statement.
        RestStatus status = response.status();
    }


}

我们会发现这种创建方式与其他版本的创建方式有那么一点不同,尤其是创建client的时候!
并不是所有的创建方式都是一样的!
创建完成后我们可以通过kibana来查看


过几天我还会有ES的 JAVA API 的各种查询希望能帮助大家!


你可能感兴趣的:(Elasticsearch5.3 用JAVA创建索引)