springboot集成es 使用x-pack

引入架包

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.5.3</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.5.3</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>x-pack-transport</artifactId>
            <version>5.5.3</version>
        </dependency>

创建客户端

    @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());
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值