1.应入相关依赖
// 添加 Spring Data Elasticsearch 的依赖
compile('org.springframework.boot:spring-boot-starter-data-elasticsearch')
// 添加 JNA 的依赖
compile('net.java.dev.jna:jna:4.3.0')
2.创建文档实体
@Document(indexName = "blog",type = "blog")
public class EcBlog implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private String id;
private String title;
private String content;
private String summary;
protected EcBlog(){
}
public EcBlog(String title, String content,String summary) {
this.title = title;
this.content = content;
this.summary = summary;
}
public EcBlog(String id, String title, String content,String summary) {
this.id = id;
this.title = title;
this.content = content;
this.summary = summary;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
@Override
public String toString() {
return String.format(
"User[id=%s, title='%s', content='%s']",
id, title, content);
}
}
3.编写Repository资源接口,继承于ElasticsearchRepository接口,编写对应方法findDistinctEcBlogByTitleOrContentContainingOrSummaryContaining(命名规则与sql同步)
public interface BlogRepository extends ElasticsearchRepository<EcBlog,String> {
/**
* 根据用户名分页查询博客列表
* @param title
* @param content
* @param pageable
* @return
*/
Page<EcBlog> findDistinctEcBlogByTitleOrContentContainingOrSummaryContaining(String title, String content,String summary, Pageable pageable);
}
4.编写Controller层代码
@RestController
@RequestMapping("/blogs")
public class BlogController {
@Autowired
private BlogRepository blogRepository;
@GetMapping
public List<EcBlog> blogList(@RequestParam(value = "title",required = false,defaultValue = "")String title,
@RequestParam(value = "content",required = false,defaultValue = "")String content,
@RequestParam(value = "summary",required = false,defaultValue = "")String summary,
@RequestParam(value = "pageIndex",required = false,defaultValue = "0")int pageIndex,
@RequestParam(value = "pageSize",required = false,defaultValue = "10")int pageSize){
Pageable pageable = new PageRequest(pageIndex,pageSize);//Distinct
Page<EcBlog> page= blogRepository.findDistinctEcBlogByTitleOrContentContainingOrSummaryContaining(title, content,summary,pageable);
return page.getContent();
}
}
5.在application.properties配置文件中加入配置
# 内嵌 Elasticsearch 实例。默认存储位置是工作目录的 elastic 目录
spring.data.elasticsearch.properties.path.home=target/elastic
# 设置连接超时时间
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
注意:在运行项目的时候,本地必须已经启动了elasticsearch,运行在9300端口。执行elasticsearch安装路径下bin文件夹中elasticsearch.bat。出现以下页面表示启动已经完成。
附上elasticsearch2.4.4的下载地址
http://www.elastic.co/downloads/past-releases/elasticsearch-2-4-4