Elasticsearch高级API-----获得客户端对象

 我用的环境是ES7.1.1、jdk1.8、gradle、springboot1.5.1

  • 引入高级api的jar包

compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.1.1'
compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-client', version: '7.1.1'
  •  springboot环境包

 

testCompile group: 'junit', name: 'junit', version: '4.12'

compile ("org.springframework.boot:spring-boot-starter:1.5.1.RELEASE")
compile ('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0')
compile ('mysql:mysql-connector-java:5.1.38')//驱动
compile group: 'com.zaxxer', name: 'HikariCP', version: '3.3.1'//连接池
compile fileTree(dir:'lib',include:['*.jar'])//这里是es里的lib
  •  将client纳入spring环境

package com.yuqi.esclient;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200));
        return new RestHighLevelClient(builder);
    }
}
  • 使用

 

package com.yuqi.server;

import com.yuqi.mapper.CarriskalarmMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class DiServier implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(DiServier.class);

    @Autowired
    RestHighLevelClient client;

    @Override
    public void run(String... args) throws Exception {

          //TODO  在这里直接使用上面注入的client

    }
}

 

你可能感兴趣的:(elasticsearch)