SpringBoot集成ElasticSearch

根据项目要求集成ES

简单DEMO例子 

maven

只需要引入es相关即可
    
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

yaml

基本配置集群名称,集群ip
spring:
  data:
     elasticsearch:
       cluster-name: SOC-15
       cluster-nodes: 10.2.4.15:9300,10.2.4.42:9300,10.2.4.43:9300

ElasticsearchRepository

这个是必须的,respository提供了一些基本的方法可以直接使用,如果需要自己定义方法,则在下面的类里面增加方法即可。
import neusoft.beans.EsBean;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;


/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 17-9-27
 * Time: 下午4:02
 * To change this template use File | Settings | File Templates.
 */
public interface EsBeanRepository extends ElasticsearchRepository {

}

与ES交互的Bean

Document注解里面有很多参数,基本的配置有索引名称,库名称,还有分片等等。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 17-9-27
 * Time: 下午4:07
 * To change this template use File | Settings | File Templates.
 */
@Document(indexName="test",type="test")
public class EsBean implements Serializable {
    @Id
    public String id;

    @Field
    public int gs;

    @Field
    public int study;

}

Service实现

下面的调用是基本的api调用,只是一个save操作
import com.alibaba.fastjson.JSON;
import neusoft.beans.EsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;


/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 17-9-27
 * Time: 下午4:34
 * To change this template use File | Settings | File Templates.
 */
@Service
@EnableElasticsearchRepositories
public class EsServiceImpl implements EsService{
    @Resource
    private EsBeanRepository esBeanRepository;

    @Override
    public String queryInfoById(String id) {
        System.out.println("id:" + id);
//        EsBean eb = (EsBean)esBeanRepository.findOne(id);
        EsBean eb = new EsBean();
        eb.gs = 250;
        eb.study=250;
        esBeanRepository.save(eb);
        String value = JSON.toJSONString(eb);
        System.out.println("value:"+value);
        return value;
    }
}

结果



其他

源码在个人的github上,感兴趣的可以看看学习 个人Github:https://github.com/GinoyJda/  

你可能感兴趣的:(ElasticSearch杂谈,SpringBoot杂谈)