In this article, we will discuss about “How to create a Spring Boot + Spring Data + Elasticsearch Example”.

Tools used in this article :

  1. Spring Boot 1.5.1.RELEASE
  2. Spring Boot Starter Data Elasticsearch 1.5.1.RELEASE
  3. Spring Data Elasticsearch 2.10.RELEASE
  4. Elasticsearch 2.4.4
  5. Maven
  6. Java 8
  7. Note
    SpringBoot 1.5.1.RELEASE and Spring Data Elasticsearch 2.10.RELEASE supports only ElasticSearch 2.4.0. They don’t support the latest version of ElasticSearch 5.x version. Read this – Spring Data Elasticsearch Spring Boot version matrix
  8. Related – Elasticsearch Basics

2. Project Dependency

Declares a spring-boot-starter-data-elasticsearch for Spring Data ElasticSearch application.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <artifactId>springboot-springdata-elasticsearch-example</artifactId>
<packaging>jar</packaging>
<url>https://www.mkyong.com</url>
<version>1.0</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- Runtime, for Embedded Elasticsearch,
comment this if connect to external elastic search server-->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<scope>runtime</scope>
</dependency> </dependencies> <build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

Review the project dependencies :

Terminal
$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springboot-springdata-elasticsearch-example 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ springboot-springdata-elasticsearch-example ---
[INFO] org.springframework.boot:springboot-springdata-elasticsearch-example:jar:1.0
[INFO] +- org.springframework.boot:spring-boot-starter-data-elasticsearch:jar:1.5.1.RELEASE:compile
[INFO] | +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] | | | +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] | | | | \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] | | | +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] | | | \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] | | \- org.yaml:snakeyaml:jar:1.17:compile
[INFO] | \- org.springframework.data:spring-data-elasticsearch:jar:2.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-context:jar:4.3.6.RELEASE:compile
[INFO] | | +- org.springframework:spring-aop:jar:4.3.6.RELEASE:compile
[INFO] | | +- org.springframework:spring-beans:jar:4.3.6.RELEASE:compile
[INFO] | | \- org.springframework:spring-expression:jar:4.3.6.RELEASE:compile
[INFO] | +- org.springframework:spring-tx:jar:4.3.6.RELEASE:compile
[INFO] | +- org.springframework.data:spring-data-commons:jar:1.13.0.RELEASE:compile
[INFO] | +- commons-lang:commons-lang:jar:2.6:compile
[INFO] | +- joda-time:joda-time:jar:2.9.7:compile
[INFO] | +- org.elasticsearch:elasticsearch:jar:2.4.4:compile
[INFO] | | +- org.apache.lucene:lucene-core:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-backward-codecs:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-analyzers-common:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-queries:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-memory:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-highlighter:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-queryparser:jar:5.5.2:compile
[INFO] | | | \- org.apache.lucene:lucene-sandbox:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-suggest:jar:5.5.2:compile
[INFO] | | | \- org.apache.lucene:lucene-misc:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-join:jar:5.5.2:compile
[INFO] | | | \- org.apache.lucene:lucene-grouping:jar:5.5.2:compile
[INFO] | | +- org.apache.lucene:lucene-spatial:jar:5.5.2:compile
[INFO] | | | +- org.apache.lucene:lucene-spatial3d:jar:5.5.2:compile
[INFO] | | | \- com.spatial4j:spatial4j:jar:0.5:compile
[INFO] | | +- com.google.guava:guava:jar:18.0:compile
[INFO] | | +- org.elasticsearch:securesm:jar:1.0:compile
[INFO] | | +- com.carrotsearch:hppc:jar:0.7.1:compile
[INFO] | | +- com.fasterxml.jackson.dataformat:jackson-dataformat-smile:jar:2.8.6:compile
[INFO] | | +- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:jar:2.8.6:compile
[INFO] | | +- com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:jar:2.8.6:compile
[INFO] | | +- io.netty:netty:jar:3.10.6.Final:compile
[INFO] | | +- com.ning:compress-lzf:jar:1.0.2:compile
[INFO] | | +- com.tdunning:t-digest:jar:3.0:compile
[INFO] | | +- org.hdrhistogram:HdrHistogram:jar:2.1.6:compile
[INFO] | | +- commons-cli:commons-cli:jar:1.3.1:compile
[INFO] | | \- com.twitter:jsr166e:jar:1.1.0:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-core:jar:2.8.6:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.6:compile
[INFO] | | \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO] | +- org.slf4j:slf4j-api:jar:1.7.22:compile
[INFO] | \- org.slf4j:jcl-over-slf4j:jar:1.7.22:compile
[INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.5.1.RELEASE:test
[INFO] | +- org.springframework.boot:spring-boot-test:jar:1.5.1.RELEASE:test
[INFO] | +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.5.1.RELEASE:test
[INFO] | +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO] | | \- net.minidev:json-smart:jar:2.2.1:test
[INFO] | | \- net.minidev:accessors-smart:jar:1.1:test
[INFO] | | \- org.ow2.asm:asm:jar:5.0.3:test
[INFO] | +- junit:junit:jar:4.12:test
[INFO] | +- org.assertj:assertj-core:jar:2.6.0:test
[INFO] | +- org.mockito:mockito-core:jar:1.10.19:test
[INFO] | | \- org.objenesis:objenesis:jar:2.1:test
[INFO] | +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] | +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] | +- org.skyscreamer:jsonassert:jar:1.4.0:test
[INFO] | | \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
[INFO] | +- org.springframework:spring-core:jar:4.3.6.RELEASE:compile
[INFO] | \- org.springframework:spring-test:jar:4.3.6.RELEASE:test
[INFO] \- net.java.dev.jna:jna:jar:4.2.2:runtime
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.867 s
[INFO] Finished at: 2017-03-14T19:55:41+08:00
[INFO] Final Memory: 27M/437M
[INFO] ------------------------------------------------------------------------

3. Spring Data ElasticSearch Application

Let us start Spring Boot + Spring Data + Elasticsearch Example now.

3.1. Develop Model for our project

package com.es;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "books", type = "books")
public class Book { @Id
private String id;
private String title;
private String author;
private String releaseDate; public Book() {
} public Book(String id, String title, String author, String releaseDate) {
this.id = id;
this.title = title;
this.author = author;
this.releaseDate = releaseDate;
} //getters and setters @Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", releaseDate='" + releaseDate + '\'' +
'}';
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getAuthor() {
return author;
} public void setAuthor(String author) {
this.author = author;
} public String getReleaseDate() {
return releaseDate;
} public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
} }
package com.es;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface BookRepository extends ElasticsearchRepository<Book, String> { Page<Book> findByAuthor(String author, Pageable pageable); List<Book> findByTitle(String title); }
package com.es;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import java.util.List; public interface BookService { Book save(Book book); void delete(Book book); Book findOne(String id); Iterable<Book> findAll(); Page<Book> findByAuthor(String author, PageRequest pageRequest); List<Book> findByTitle(String title); }
package com.es;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class BookServiceImpl implements BookService { private BookRepository bookRepository; @Autowired
public void setBookRepository(BookRepository bookRepository) {
this.bookRepository = bookRepository;
} public Book save(Book book) {
return bookRepository.save(book);
} public void delete(Book book) {
bookRepository.delete(book);
} public Book findOne(String id) {
return bookRepository.findOne(id);
} public Iterable<Book> findAll() {
return bookRepository.findAll();
} public Page<Book> findByAuthor(String author, PageRequest pageRequest) {
return bookRepository.findByAuthor(author, pageRequest);
} public List<Book> findByTitle(String title) {
return bookRepository.findByTitle(title);
} }
package com.es;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList;
import java.util.List; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*; @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class BookServiceTest { @Autowired
private BookService bookService; @Autowired
private ElasticsearchTemplate esTemplate; @Before
public void before() {
esTemplate.deleteIndex(Book.class);
esTemplate.createIndex(Book.class);
esTemplate.putMapping(Book.class);
esTemplate.refresh(Book.class);
} @Test
public void testSave() { Book book = new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017");
Book testBook = bookService.save(book); assertNotNull(testBook.getId());
assertEquals(testBook.getTitle(), book.getTitle());
assertEquals(testBook.getAuthor(), book.getAuthor());
assertEquals(testBook.getReleaseDate(), book.getReleaseDate()); } @Test
public void testFindOne() { Book book = new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017");
bookService.save(book); Book testBook = bookService.findOne(book.getId()); assertNotNull(testBook.getId());
assertEquals(testBook.getTitle(), book.getTitle());
assertEquals(testBook.getAuthor(), book.getAuthor());
assertEquals(testBook.getReleaseDate(), book.getReleaseDate()); } @Test
public void testFindByTitle() { Book book = new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017");
bookService.save(book); List<Book> byTitle = bookService.findByTitle(book.getTitle());
assertThat(byTitle.size(), is(1));
} @Test
public void testFindByAuthor() { List<Book> bookList = new ArrayList<>(); bookList.add(new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017"));
bookList.add(new Book("1002", "Apache Lucene Basics", "Rambabu Posa", "13-MAR-2017"));
bookList.add(new Book("1003", "Apache Solr Basics", "Rambabu Posa", "21-MAR-2017"));
bookList.add(new Book("1007", "Spring Data + ElasticSearch", "Rambabu Posa", "01-APR-2017"));
bookList.add(new Book("1008", "Spring Boot + MongoDB", "Mkyong", "25-FEB-2017")); for (Book book : bookList) {
bookService.save(book);
} Page<Book> byAuthor = bookService.findByAuthor("Rambabu Posa", new PageRequest(0, 10));
assertThat(byAuthor.getTotalElements(), is(4L)); Page<Book> byAuthor2 = bookService.findByAuthor("Mkyong", new PageRequest(0, 10));
assertThat(byAuthor2.getTotalElements(), is(1L)); } @Test
public void testDelete() { Book book = new Book("1001", "Elasticsearch Basics", "Rambabu Posa", "23-FEB-2017");
bookService.save(book);
bookService.delete(book);
Book testBook = bookService.findOne(book.getId());
assertNull(testBook);
} }
package com.es;

import org.elasticsearch.client.Client;
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.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import java.net.InetAddress; @Configuration
@EnableElasticsearchRepositories(basePackages = "com.es")
public class EsConfig { @Value("${elasticsearch.host}")
private String EsHost; @Value("${elasticsearch.port}")
private int EsPort; @Value("${elasticsearch.clustername}")
private String EsClusterName; @Bean
public Client client() throws Exception { Settings settings = Settings.builder().put("cluster.name", this.EsClusterName).build(); //https://www.elastic.co/guide/en/elasticsearch/guide/current/_transport_client_versus_node_client.html TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(EsHost), EsPort));
return client; } @Bean
public ElasticsearchTemplate elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
} //Embedded Elasticsearch Server
/*@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(nodeBuilder().local(true).node().client());
}*/ }

配置文件:

elasticsearch.clustername =myelasticsearch
elasticsearch.host = localhost
elasticsearch.port = 9300 #
# Home directory of the embedded Elasticsearch instance. Default to the
# current working directory.
#
#spring.data.elasticsearch.properties.path.home=target/elastic-embedded
#spring.data.elasticsearch.properties.transport.tcp.connect_timeout=60s

源码地址:https://github.com/wangchuanfu/springboot-elasticsearch

springboot 集成elasticsearch的更多相关文章

  1. springboot集成elasticsearch

    在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用: 在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理: 第 ...

  2. SpringBoot 集成 Elasticsearch

    前面在 ubuntu 完成安装 elasticsearch,现在我们SpringBoot将集成elasticsearch. 1.创建SpringBoot项目 我们这边直接引入NoSql中Spring ...

  3. ElasticSearch(八):springboot集成ElasticSearch集群并使用

    1. 集群的搭建 见:ElasticSearch(七) 2. springboot配置集群 2.1 创建springboot项目,使用idea创建,不过多介绍(创建项目时候建议不要勾选elastics ...

  4. springBoot集成Elasticsearch抛出Factory method 'restHighLevelClient' threw exception; nested exception is java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restHighLeve ...

  5. ElasticSearch(十):springboot集成ElasticSearch集群完成数据的增,删,改

    前言 之前介绍了使用devTools进行索引库数据的crud,这里使用的是java程序,使用中间件activeMQ进行数据库和索引库数据的同步.主要是用来完成对数据库的修改来完成对索引库的同步. 正文 ...

  6. Springboot 集成 ElasticSearch 踩坑

    这里只涉及到基础使用 导包 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...

  7. SpringBoot 集成Elasticsearch进行简单增删改查

    一.引入的pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...

  8. springboot集成elasticsearch遇到的问题

    public interface EsBlogRepository extends ElasticsearchRepository<EsBlog,String>{ Page<EsBl ...

  9. springboot集成elk 一: springboot + Elasticsearch

    1.ELK介绍 1> Elasticsearch是实时全文搜索和分析引擎, 提供搜集.分析.存储数据三大功能: 是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统. ...

随机推荐

  1. Ubuntu 地址导航栏修改为显示路径及如何恢复原模式?

    在Ubuntu中,文件位置默认不是和Windows地址栏一样的(位置项),而是显示是路径名称组合(路径栏),这对于文件路径的获得复制很不方便.比如,获得某个文件德 路径,如果是地址栏,直接复制一下就可 ...

  2. 深入浅出SIP协议

    传统电话是电磁波的通信,当电话技术发展到IP技术时代,SIP协议成为了电话通信标准协议,不仅可以通电话.还可以收发信息.视频.开会.放PPT.事实上,今天的通信业已全面采用SIP协议作为通信标准,无论 ...

  3. java SoftReference WeakReference

    Java 2 平台引入了 java.lang.ref 包,其中包括的类可以让您引用对象,而不将它们留在内存中.这些类还提供了与垃圾收集器(garbage collector)之间有限的交互. 1.先“ ...

  4. JDBC是什么?

    JDBC代表Java数据库连接(Java Database Connectivity),它是用于Java编程语言和数据库之间的数据库无关连接的标准Java API,换句话说:JDBC是用于在Java语 ...

  5. java EE 环境配置(JDK + Tomcat + Eclipse for java EE)

    这学期的课程多数都是java语言的,像Java Web程序设计,java课程设计案例,所以趁周末先把软件,环境配置好. 下载JDK 先给上下载链接:http://www.oracle.com/tech ...

  6. [原创] GSM/GPRS 以及CDMA区分以及相关模块选型

  7. spark LinearRegression 预测缺失字段的值

    最近在做金融科技建模的时候,字段里面很多缺少值得时候,模型对于新用户的预测会出现很大的不稳定,即PSI较大的情况. 虽然我们依据字段IV值得大小不断的在调整字段且开发新变量,但是很多IV值很大的字段直 ...

  8. scala 日期格式转换

    scala> val format = new java.text.SimpleDateFormat("dd-MM-yyyy") 注意MM必须要大写 format: java ...

  9. 新浪股票接口AndroidSDK

    昨天想到一个点子,需要访问股票行情.于是在网上搜了一下免费的股市行情的接口.发现新浪股票的数据接口比较稳定,于是就用它了. 网上对于新浪股票的数据接口介绍比较详细,并且实现也很简单,所以花了一下午就基 ...

  10. PDCA 价值所在

    企业IT服务管理实施 不提倡一步到位 对企业IT部门来说,实施ITIL Service Support(服务支持)的意义在于清晰梳理日常IT运维管理过程中遇到的各种各样的事,使IT运维过程变得有序连贯 ...