springboot集成es 使用x-pack

引入架包

        
            org.elasticsearch
            elasticsearch
            5.5.3
        

        
            org.elasticsearch.client
            transport
            5.5.3
        

        
            org.elasticsearch.client
            x-pack-transport
            5.5.3
        

创建客户端

    @Bean
    @Scope
    public TransportClient TransportClients() throws Exception{

        // 9300是es的tcp服务端口
        InetSocketTransportAddress node = new InetSocketTransportAddress(
                InetAddress.getByName("127.0.0.1"),
                9300);

        // 设置es节点的配置信息
        Settings settings = Settings.builder()
                .put("cluster.name", "es-5.0-test")
                .build();

        // 实例化es的客户端对象
        return new PreBuiltTransportClient(settings).addTransportAddress(node);
    }

索引文档

    @Autowired
    private TransportClient client;

    public void insertEs1() throws Exception {
        //创建对象
        XContentBuilder xContentBuilder = jsonBuilder()
                .startObject()
                .field("first_name", "John")
                .field("last_name", "Smith")
                .field("age", 25)
                .field("body", "I love to go rock climbing")
                .field("about", "20130801175520")
                .field("valid", true)
                .endObject();

        String index = "megacorp";
        String type = "employee";
        String id = "1"; // UUID.randomUUID().toString().replace("-", "");
        IndexResponse response = client.prepareIndex(index, type, id)
                .setSource(xContentBuilder)
                .execute().actionGet();

        System.out.println("添加成功    " + response.getId());
    }

    public void insertEs2() throws Exception {

        String index = "megacorp";
        String type = "employee";
        String id = "1"; // UUID.randomUUID().toString().replace("-", "");
        JSONObject object = new JSONObject();
        IndexResponse response = client.prepareIndex(index, type, id)
                .setSource(object)
                .execute().actionGet();

        System.out.println("添加成功    " + response.getId());
    }

你可能感兴趣的:(elasticSearch)