[From] http://www.tuicool.com/articles/JBvQrmj

本文讲解Spring Boot基础下,如何使用 ElasticSearch,实现全文搜索。

版本须知

spring data elasticSearch 的版本与Spring boot、Elasticsearch版本需要匹配。

Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
x <= 1.3.5 y <= 1.3.4 z <= 1.7.2
x >= 1.4.x 2.0.0 <=y <5.0.0 2.0.0 <= z < 5.0.0

环境依赖

修改 POM 文件,添加 spring-boot-starter-data-elasticsearch 依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

数据源

方案一 使用 Spring Boot 默认配置

在 src/main/resources/application.properties 中配置数据源信息。

spring.data.elasticsearch.properties.host = 127.0.0.1
spring.data.elasticsearch.properties.port = 9300

通过 Java Config 创建ElasticSearchConfig。

@Configuration
@EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
public class ElasticSearchConfig {}

方案二 手动创建

通过 Java Config 创建ElasticSearchConfig。

@Configuration
@EnableElasticsearchRepositories("com.lianggzone.springboot.action.data.elasticsearch")
public class ElasticsearchConfig2 { private String hostname = "127.0.0.1";
private int port = 9300; @Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
} @Bean
public Client client() {
TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(hostname, port); client.addTransportAddress(address);
return client;
}
}

业务操作

实体对象

@Document(indexName = "springbootdb", type = "news")
public class News { @Id
private String id; private String title; private String content; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
@Field(type = FieldType.Date, format = DateFormat.basic_date_time, index = FieldIndex.not_analyzed)
@CreatedDate
private Date createdDateTime; // GET和SET方法
}

DAO相关

public interface NewsRepository extends ElasticsearchRepository<News, String> {
public List<News> findByTitle(String title);
}

Service相关

我们来定义实现类,Service层调用Dao层的方法,这个是典型的套路。

@Service
public class NewsService { @Autowired
private NewsRepository newsRepository; public Iterable<News> findAll(){
return newsRepository.findAll();
} public Iterable<News> search(QueryBuilder query){
return newsRepository.search(query);
} public List <News> findByTitle(String title) {
return this.newsRepository.findByTitle(title);
} public void deleteAll(String id){
this.newsRepository.delete(id);
} public void init(){
for (int i = 0; i < 100; i++) {
News news = new News();
news.setId(i+"");
news.setTitle(i + ".梁桂钊单元测试用例");
news.setContent("梁桂钊单元测试用例"+i+"xxxxx");
news.setCreatedDateTime(new Date());
this.newsRepository.save(news);
}
}
}

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

@RestController
@RequestMapping(value="/data/elasticsearch/news")
public class NewsController { @Autowired
private NewsService newsService; /**
* 初始化
* @param request
*/
@RequestMapping(value = "/init", method = RequestMethod.POST)
public void init(HttpServletRequest request) {
this.newsService.init();
} /**
* findAll
* @param request
* @return
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public Map<String, Object> findList(HttpServletRequest request) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("items", this.newsService.findAll());
return params;
} /**
* find
* @param request
* @return
*/
@RequestMapping(value = "/{title}", method = RequestMethod.GET)
public Map<String, Object> search(@PathVariable String title) {
// 构建查询条件
QueryBuilder queryBuilder = QueryBuilders.queryString(title); // Pekkle: spring boot 1.4.1 集成elastic search后看不到此方法,用如下方法代替。
QueryBuilder queryBuilder = QueryBuilders.simpleQueryStringQuery(title);
Map<String, Object> params = new HashMap<String, Object>(); params.put("items", this.newsService.search(queryBuilder)); return params; } }

总结

上面这个简单的案例,让我们看到了 Spring Boot 整合 ElasticSearch 流程如此简单。

[转] Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

  2. Spring Boot 揭秘与实战(二) 数据缓存篇 - Guava Cache

    文章目录 1. Guava Cache 集成 2. 个性化配置 3. 源代码 本文,讲解 Spring Boot 如何集成 Guava Cache,实现缓存. 在阅读「Spring Boot 揭秘与实 ...

  3. Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

    文章目录 1. EhCache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 EhCache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门 ...

  4. Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门

    文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...

  5. Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理

    文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...

  6. Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch

    文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...

  8. Spring Boot 揭秘与实战(二) 数据存储篇 - Redis

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...

  9. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  10. Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...

随机推荐

  1. 关于Rest Framework中View、APIView与GenericAPIView的对比分析

    关于Rest Framework中View.APIView与GenericAPIView的对比分析  https://blog.csdn.net/odyssues_lee/article/detail ...

  2. Reading——The Non-Designer's Design Book

    看这本书的时候真的好恨没有CS7在手><,不然我百度几张图来模拟下,体验下设计的快感. 人们总是很容易注意到在他们潜意识里存在的东西,比如说这个图:    我们很容易联想到微信,但是3   ...

  3. C# JSON使用的常用技巧(二)

    JSON在php里一句json_encode就可以得到 在C#里我们同样也很容易的可以得到 用到的类库:Newtonsoft.Json.dll 实体类: class Cat { public stri ...

  4. GlobalAlloc()和malloc()、HeapAlloc()

    两者都是在堆上分配内存区.  malloc()是C运行库中的动态内存分配函数,WINDOWS程序基本不使用了,因为它比WINDOWS内存分配函数少了一些特性,如,整理内存.  GlobalAlloc( ...

  5. Mono for Android for Visual Studio 2010安装及试用

    安装 Mono for Android for Visual Studio 2010 需要下面4个步骤: 1.安装 JDK 下载并安装 Java 1.6 (Java 6) JDK. 2.安装 Andr ...

  6. 停止Nginx服务

    查询nginx进程信息 chen@ubuntu:~$ ps -ef |grep nginx root : ? :: nginx: master process /usr/sbin/nginx -g d ...

  7. [.net 多线程]AutoResetEvent, ManualResetEvent

    ManualResetEvent: 通知一个或多个正在等待的线程已发生事件,允许线程通过发信号互相通信,来控制线程是否可心访问资源. Set() : 用于向 ManualResetEvent 发送信号 ...

  8. WPF 控件库——带有惯性的ScrollViewer

    WPF 控件库系列博文地址: WPF 控件库——仿制Chrome的ColorPicker WPF 控件库——仿制Windows10的进度条 WPF 控件库——轮播控件 WPF 控件库——带有惯性的Sc ...

  9. Dapper ORM

    参考地址:https://www.cnblogs.com/lunawzh/p/6607116.html 1.连接语句 var conn = new SqlConnection(Configuratio ...

  10. mysql相关的软件

    数据库采用mysql,那么问题来了,mysql的部署是采用主备模式?主主模式?集群模式?在然后采取分库.分表模式? 其次:在外围的辅助开源软件的选择mycat?mybatis?keepalived?r ...