目录
1.添加关于elasticsearch的依赖:
2.application.yml配置关于es连接信息
3.定义数据的model对象:
4.定义接口,继承ElasticsearchRepository
5.定义业务操作接口
6.具体的业务实现
7.定义接口controller
8.启动服务,测试效果
9.备注
上一篇文章简单的介绍了elasticsearch,下面重点展示springboot整合es的方式:本文使用springboot自身的依赖来实现:
为了数据查看的方便,我们使用elasticsearch-head-master页面插件来查看数据,当然,也可以使用kibana进行查看;
项目版本信息:
elasticsearch:5.6.0
springboot:2.1.4.RELEASE
下面是具体的编码示例:
1.添加关于elasticsearch的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.application.yml配置关于es连接信息
spring:
data:
elasticsearch:
cluster-name: elasticsearch
# Java连接es需要用端口号9300
cluster-nodes: localhost:9300
repositories:
enabled: true
3.定义数据的model对象:
我们往ES中添加书本的一些简单信息
package com.demo.elasticsearch.elasticsearch;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "book",type = "doc",shards = 5,replicas = 1)
public class Book {
@Id
private String id;
/**
* 中文分词设置,前提是您的es已经安装了中文分词ik插件
* 中文分词有两种形式:
* ik_max_word:会将文本做最细粒度的拆分
* ik_smart:会将文本做最粗粒度的拆分
*/
@Field(type = FieldType.Text, analyzer = "ik_max_word",searchAnalyzer ="ik_max_word")
private String title;
private String author;
private String postDate;
}
4.定义接口,继承ElasticsearchRepository
package com.demo.elasticsearch.elasticsearch;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookRepository extends ElasticsearchRepository<Book,String> {
// 根据作者名称查询书包集合
Page<Book> findByAuthor(String author, Pageable pageable);
}
5.定义业务操作接口
public interface BookService {
Optional<Book> findById(String id);
Book save(Book blog);
void delete(Book blog);
Optional<Book> findOne(String id);
List<Book> findAll();
// 根据作者查询
Page<Book> findByAuthor(String author, PageRequest pageRequest);
// 根据书的主题中某个字段查询
Result findByTitle(String author);
}
6.具体的业务实现
package com.demo.elasticsearch.service.impl;
import com.demo.elasticsearch.dto.Result;
import com.demo.elasticsearch.elasticsearch.Book;
import com.demo.elasticsearch.elasticsearch.BookRepository;
import com.demo.elasticsearch.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Autowired
ElasticsearchTemplate elasticsearchTemplate;
@Override
public Optional<Book> findById(String id) {
return bookRepository.findById(id);
}
@Override
public Book save(Book book) {
return bookRepository.save(book);
}
@Override
public void delete(Book book) {
bookRepository.delete(book);
}
@Override
public Optional<Book> findOne(String id) {
return bookRepository.findById(id);
}
@Override
public List<Book> findAll() {
return (List<Book>)bookRepository.findAll();
}
/**
* 根据作者字段查询
* @param author
* @param pageRequest
* @return
*/
@Override
public Page<Book> findByAuthor(String author, PageRequest pageRequest) {
return bookRepository.findByAuthor(author,pageRequest);
}
// 前几种都是通过bookRepository去操作,其有一定的局限性,下面这种方法是通过具拼接查询语句的形式实现,方便各种精确,模糊匹配查询
/**
* 根据书的主题查询
* @param title
* @return
*/
@Override
public Result findByTitle(String title) {
log.info("");
String json = "{\n" +
" \"match\" : {\n" +
" \"title\" : " + "\"" + title + "\"\n"+
" }\n" +
" }";
log.info("hql语句格式==={}",json);
// 创建es查询请求
StringQuery query = new StringQuery(json);
query.addIndices("book"); // 添加index
query.addTypes("doc"); // 添加type
List<Book> books = elasticsearchTemplate.queryForList(query, Book.class);
return Result.ok(books);
}
}
7.定义接口controller
package com.demo.elasticsearch.controller;
import com.demo.elasticsearch.dto.Result;
import com.demo.elasticsearch.elasticsearch.Book;
import com.demo.elasticsearch.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Api(tags = "ES测试模块")
@RestController
@Slf4j
@RequestMapping("/book")
public class ElasticSearchController {
@Autowired
private BookService bookService;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@ApiOperation(value = "创建索引",notes = "创建索引")
@PostMapping("/create")
public Result createIndex(){
log.info("创建索引");
boolean index = elasticsearchTemplate.createIndex(Book.class);
return Result.ok(index);
}
@ApiOperation(value = "插入数据",notes = "插入数据")
@PostMapping("/save")
public Result Save(@RequestBody Book book) {
log.info("插入数据的入参==={}",book.toString());
Book save = bookService.save(book);
return Result.ok("新增数据成功");
}
@ApiOperation(value = "根据id查询",notes = "根据id查询")
@PostMapping("/id")
public Result getBookById(@RequestBody Book request) {
log.info("根据id查询入参=={}",request.toString());
Optional<Book> opt = bookService.findById(request.getId());
Book book = opt.get();
log.info("根据id查询的结果==={}",book.toString());
return Result.ok(book);
}
@ApiOperation(value = "根据作者名字段查询",notes = "根据作者名字段查询")
@PostMapping("/author")
public Result getBookByAuthor(@RequestBody Book request) {
log.info("根据作者精确查询入参=={}",request.toString());
PageRequest pageRequest = new PageRequest(0,2);
Page<Book> byAuthor = bookService.findByAuthor(request.getAuthor(), pageRequest);
List<Book> content = byAuthor.getContent();
log.info("根据id查询的结果==={}",byAuthor.toString());
return Result.ok(content);
}
@ApiOperation(value = "根据书主题字段查询",notes = "根据书主题字段查询")
@PostMapping("/title")
public Result getBookByTitle(@RequestBody Book request) {
log.info("根据书主题字段查询入参=={}",request.toString());
Result byTitle = bookService.findByTitle(request.getTitle());
return Result.ok(byTitle);
}
}
8.启动服务,测试效果
8.1:首先我们调用创建索引的接口:/book/create,如果执行成功,我们可以看到红圈中的book索引,说明索引创建成功;
8.2:我们往其中插入一些数据:方便后续查询使用:通过head插件的查询url: http://localhost:9200/book/_search,以表格视图的格式展示,数据如下:
8.3:通过作者查询:查询作者中有tom字段的书本
8.4:通过title查询:该方法的serviceImpl是通过拼接查询语句的方式,和查询作者的方式有所区别:
9.备注
本文只是展示了springboot整合Elasticsearch最基本的使用方式,实际项目中,为了满足各种使用场景,可能会对查询语句进行单独的设计和封装,以此满足复杂的查询匹配条件。
想要该问介绍项目源码的可以访问地址:https://github.com/yangshilei/springCloud.git
如果觉得head用的不过瘾的,可以使用kibana进行查询,效果差不多,但是kibana用途远不止于此!
好了,今天就介绍那么多了,不想写了,睡觉充电去!