1. springboot版本:1.5.9     elasticsearch版本:5.6.1    jdk:1.8

  2. pom.xml添加elasticsearch依赖

     
        2.8.2
        2.8.2
        5.6.1
        5.6.1


         org.apache.logging.log4j
         log4j-api
         ${log4j-api.version}
     

     
         org.apache.logging.log4j
         log4j-core
         ${log4j-core.version}
     

     
         org.elasticsearch
         elasticsearch
         ${elasticsearch.version}
     

     
         org.elasticsearch.client
         transport
         ${transport.version}
     


  3. application.properties添加elasticsearch配置
    spring.data.elasticsearch.cluster-name=elasticsearch
    spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
  4. 添加elasticsearch配置文件ElasticsearchConfiguration
    package com.example.demo.config;
    import org.elasticsearch.client.transport.TransportClient;
    import org.elasticsearch.common.settings.Settings;
    import org.elasticsearch.common.transport.InetSocketTransportAddress;
    import org.elasticsearch.transport.client.PreBuiltTransportClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.DisposableBean;
    import org.springframework.beans.factory.FactoryBean;
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    /**
    * @Author 冯战魁
    * @Date 2018/3/13 下午5:55
    */
    @Configuration
    public class ElasticsearchConfiguration implements FactoryBean, InitializingBean, DisposableBean {
       private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfiguration.class);
       @Value("${spring.data.elasticsearch.cluster-nodes}")
       private String clusterNodes ;

       @Value("${spring.data.elasticsearch.cluster-name}")
       private String clusterName;

       private TransportClient client;

       @Override
       public void destroy() throws Exception {
           try {
               logger.info("Closing elasticSearch client");
               if (client != null) {
                   client.close();
               }
           } catch (final Exception e) {
               logger.error("Error closing ElasticSearch client: ", e);
           }
       }

       @Override
       public TransportClient getObject() throws Exception {
           return client;
       }

       @Override
       public Class getObjectType() {
           return TransportClient.class;
       }

       @Override
       public boolean isSingleton() {
           return false;
       }

       @Override
       public void afterPropertiesSet() throws Exception {
           buildClient();
       }

       protected void buildClient()  {
           try {
               PreBuiltTransportClient  preBuiltTransportClient = new PreBuiltTransportClient(settings());
               if (!"".equals(clusterNodes)){
                   for (String nodes:clusterNodes.split(",")) {
                       String InetSocket [] = nodes.split(":");
                       String  Address = InetSocket[0];
                       Integer  port = Integer.valueOf(InetSocket[1]);
                       preBuiltTransportClient.addTransportAddress(new
                               InetSocketTransportAddress(InetAddress.getByName(Address),port ));
                   }
                   client = preBuiltTransportClient;
               }
           } catch (UnknownHostException e) {
               logger.error(e.getMessage());
           }
       }
       /**
        * 初始化默认的client
        */
       private Settings settings(){
           Settings settings = Settings.builder()
                   .put("cluster.name",clusterName)
                   .put("client.transport.sniff",true)
           .build();
           client = new PreBuiltTransportClient(settings);
           return settings;
       }
    }
  5. 添加测试接口,本例的Index是information,type是article
    package com.example.demo.controller;

    import org.elasticsearch.action.get.GetResponse;
    import org.elasticsearch.action.index.IndexResponse;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.action.search.SearchType;
    import org.elasticsearch.client.transport.TransportClient;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.SearchHits;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    /**
    * @Author 冯战魁
    * @Date 2018/3/9 下午12:13
    */
    @RestController
    @RequestMapping("/es")
    public class ElasticsearchController {
       @Autowired
       private TransportClient client;
    //    获取单条记录
       @RequestMapping("/get")
       public GetResponse hello(){
           GetResponse response = client.prepareGet("information", "article", "1").get();
           return response;
       }
    //    插入数据
       @RequestMapping("/save")
       public String save(){
           Map map = new HashMap();
           map.put("id","2");
           map.put("name","hehe");
           map.put("age",18);
           IndexResponse response = client.prepareIndex("information", "article",map.get("id").toString())
                   .setSource(map).execute().actionGet();
           return response.getId();
       }
    //    查询搜索
       @RequestMapping("/search")
       public List search(){
           SearchResponse response = client.prepareSearch("information")
                   .setTypes("article")
                   .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
    //                .setQuery(QueryBuilders.termQuery("name", "feng"))                 // Query
                   .setPostFilter(QueryBuilders.rangeQuery("age").from(0).to(188))     // Filter
                   .setFrom(0).setSize(60).setExplain(true)
                   .get();
    //        SearchResponse response =client.prepareSearch().execute().actionGet();
           SearchHits searchHits = response.getHits();
           System.err.println("总数:"+searchHits.getTotalHits());
           List data = new ArrayList();
           SearchHit[] hits = searchHits.getHits();
           for (SearchHit hit : hits) {
               String json = hit.getSourceAsString();
               data.add(json);
               System.err.println(json);
           }
           return data;
       }

    }
  6. 启动elasticsearch和springboot,访问测试接口