添加依赖 gradle
compile("org.springframework.boot:spring-boot-starter-data-elasticsearch:${springBootVersion}")
只要加入依赖后springboot就可以自动加载相关操作了,基本使用方式如下
application.properties 中可以配置es的一些动作,下面只列举部分,详细的可以看官网
# ELASTICSEARCH (ElasticsearchProperties})
#spring.data.elasticsearch.cluster-name=es-cluster-local
# The address(es) of the server node (comma-separated; if not specified starts a client node)
#spring.data.elasticsearch.cluster-nodes=192.168.30.129:9300
# if local mode should be used with client nodes
#spring.data.elasticsearch.local=true
# if spring data repository support is enabled
#spring.data.elasticsearch.repositories.enabled=true
下面列举一个简单例子,有使用了lombok要先在idea中安装插件才可以使用
package cn.xiaojf.today.data.es.entity; import lombok.Builder; import lombok.Data; /** * @author xiaojf 2016/12/14 20:07. */ @Builder @Data public class Tag { private String id; private String name; }
package cn.xiaojf.today.data.es.entity; import lombok.Builder; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.Date; import java.util.List; /** * @author xiaojf 2016/12/14 11:02. */ @Builder @Data @Document(indexName = "syslog",type = "2016-12-14",shards = 5,replicas = 1) public class SysLog { @Id private String id; @Version private Long version; private String logType; @Field(type = FieldType.Ip) private String ip; private String content; @Field(type = FieldType.Date) private Date logTime; @Field(type = FieldType.Nested) private List<Tag> tags; }
package cn.xiaojf.today.data.es.repository; import cn.xiaojf.today.data.es.entity.SysLog; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; /** * @author xiaojf 2016/12/14 20:09. */ public interface SysLogRepository extends ElasticsearchRepository<SysLog,String> { }
package cn.xiaojf.today.web.controller; import cn.xiaojf.today.data.es.entity.SysLog; import cn.xiaojf.today.data.es.entity.Tag; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author xiaojf 2016/12/14 20:10. */ @RestController @RequestMapping("/es") public class EsController { // @Autowired // private SysLogService logService; @RequestMapping("/add") @ResponseBody public void add() { Tag tag = Tag.builder().name("xiaojf").build(); List<Tag> tags = new ArrayList<>(); tags.add(tag); tags.add(tag); SysLog log = SysLog.builder() .ip("172.16.29.193") .content("测试日志") .logTime(new Date()) .tags(tags) .build(); // logService.add(log); } }
只要简单的几个操作,就可以插入数据到es,非常简单