1. 新增依赖
我本地使用的spring boot版本为1.5.8.RELEASE
compile("org.springframework.boot:spring-boot-starter-data-elasticsearch")
2. 新增配置
application.yml新增关于es的一些配置
# elasticsearch
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
3. 新增model
package com.mk.model;
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.FieldIndex;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.Date;
@Document(indexName = "mk_spring_es", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
public class ArticleInfo {
@Id
private String id;
@Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
private String articleAuthor;
@Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
private String articleTitle;
@Field(type = FieldType.String, store = true, analyzer = "ik", index = FieldIndex.analyzed)
private String articleContent;
@Field
private Date createTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getArticleAuthor() {
return articleAuthor;
}
public void setArticleAuthor(String articleAuthor) {
this.articleAuthor = articleAuthor;
}
public String getArticleTitle() {
return articleTitle;
}
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
}
public String getArticleContent() {
return articleContent;
}
public void setArticleContent(String articleContent) {
this.articleContent = articleContent;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArticleInfo that = (ArticleInfo) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (articleAuthor != null ? !articleAuthor.equals(that.articleAuthor) : that.articleAuthor != null)
return false;
if (articleTitle != null ? !articleTitle.equals(that.articleTitle) : that.articleTitle != null) return false;
if (articleContent != null ? !articleContent.equals(that.articleContent) : that.articleContent != null)
return false;
return createTime != null ? createTime.equals(that.createTime) : that.createTime == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (articleAuthor != null ? articleAuthor.hashCode() : 0);
result = 31 * result + (articleTitle != null ? articleTitle.hashCode() : 0);
result = 31 * result + (articleContent != null ? articleContent.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ArticleInfo{" +
"id='" + id + '\'' +
", articleAuthor='" + articleAuthor + '\'' +
", articleTitle='" + articleTitle + '\'' +
", articleContent='" + articleContent + '\'' +
", createTime=" + createTime +
'}';
}
}
4. 新增dao
package com.mk.dao;
import com.mk.model.ArticleInfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
@Component("elasticsearchArticleDao")
public interface ElasticsearchArticleDao extends ElasticsearchRepository<ArticleInfo, String> {
}
5. 新增service
package com.mk.service;
import com.mk.entity.Page;
import com.mk.model.ArticleInfo;
import java.util.List;
public interface ElasticsearchArticleService {
void createMapping() throws Exception;
// 保存一条数据
void saveArticle(ArticleInfo info);
// 保存多条数据
void saveArticles(List<ArticleInfo> list);
// 根据ID获取文章
ArticleInfo findArticleInfoById(String id);
// 根据关键字查询
List<ArticleInfo> findAllArticle();
// 根据关键字查询
List<ArticleInfo> findArticleByKeyword(String keyword);
// 根据关键字查询(分页)
Page<ArticleInfo> findArticleByKeywordWithPage(String keyword, int pageNo, int pageSize);
}
6. 新增service实现
package com.mk.service.impl;
import com.mk.dao.ElasticsearchArticleDao;
import com.mk.entity.Page;
import com.mk.model.ArticleInfo;
import com.mk.service.ElasticsearchArticleService;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service("elasticsearchArticleService")
public class ElasticsearchArticleServiceImpl implements ElasticsearchArticleService{
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchArticleServiceImpl.class);
@Resource
private ElasticsearchArticleDao elasticsearchArticleDao;
@Resource
private ElasticsearchTemplate elasticsearchTemplate;
@Override
public void createMapping() throws Exception{
String index = "mk_spring_es";
String type = "article";
elasticsearchTemplate.getClient().admin().indices().prepareCreate(index).execute().actionGet();
XContentBuilder builder= XContentFactory.jsonBuilder()
.startObject()
.startObject(type)
.startObject("properties")
.startObject("articleTitle").field("type", "string").field("store", "yes").field("analyzer","ik").field("index","analyzed").endObject()
.startObject("articleContent").field("type", "string").field("store", "yes").field("analyzer","ik").field("index","analyzed").endObject()
.endObject()
.endObject()
.endObject();
PutMappingRequest mapping = Requests.putMappingRequest(index).type(type).source(builder);
elasticsearchTemplate.getClient().admin().indices().putMapping(mapping).actionGet();
}
@Override
public void saveArticle(ArticleInfo info) {
info.setCreateTime(new Date());
elasticsearchArticleDao.save(info);
}
@Override
public void saveArticles(List<ArticleInfo> list) {
for (ArticleInfo info : list) {
info.setCreateTime(new Date());
}
elasticsearchArticleDao.save(list);
}
@Override
public ArticleInfo findArticleInfoById(String id) {
return elasticsearchArticleDao.findOne(id);
}
@Override
public List<ArticleInfo> findAllArticle() {
Iterable<ArticleInfo> iterable = elasticsearchArticleDao.search(QueryBuilders.matchAllQuery());
List<ArticleInfo> list = new ArrayList<>();
if(iterable != null){
iterable.forEach(list::add);
}
return list;
}
@Override
public List<ArticleInfo> findArticleByKeyword(String keyword) {
logger.info("query by keyword:{}",keyword);
HighlightBuilder.Field field = new HighlightBuilder.Field("articleTitle");
field.preTags("<span>");
field.postTags("</span>");
HighlightBuilder.Field[] fields = {field};
QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "articleAuthor", "articleTitle", "articleContent");
SortBuilder sortBuilder = new FieldSortBuilder("createTime");
sortBuilder.order(SortOrder.DESC);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.withHighlightFields(fields)
.withSort(sortBuilder)
.build();
List<ArticleInfo> list = new ArrayList<>();
Iterable<ArticleInfo> iterable = elasticsearchArticleDao.search(searchQuery);
if(iterable != null){
iterable.forEach(list::add);
}
return list;
}
@Override
public Page<ArticleInfo> findArticleByKeywordWithPage(String keyword, int pageNo, int pageSize) {
Page<ArticleInfo> result = new Page<>();
result.setPageNo(pageNo);
result.setPageSize(pageSize);
// 查询
QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "articleAuthor", "articleTitle", "articleContent");
// 分页
Pageable pageable = new PageRequest(pageNo-1, pageSize);
// 排序
SortBuilder sortBuilder = new FieldSortBuilder("createTime");
sortBuilder.order(SortOrder.DESC);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.withPageable(pageable)
.withSort(sortBuilder)
.build();
org.springframework.data.domain.Page<ArticleInfo> queryResult = elasticsearchArticleDao.search(searchQuery);
if(queryResult.getTotalElements() > 0){
List<ArticleInfo> list = new ArrayList<>();
queryResult.forEach(list::add);
result.setTotal(Long.valueOf(queryResult.getTotalElements()).intValue());
result.setList(list);
}
return result;
}
}
7. 新增controller
package com.mk.controller;
import com.mk.entity.Page;
import com.mk.entity.Response;
import com.mk.model.ArticleInfo;
import com.mk.model.User;
import com.mk.service.ElasticsearchArticleService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/article")
public class ArticleController {
@Resource
private ElasticsearchArticleService elasticsearchArticleService;
@ApiOperation(value = "创建mapping",notes = "创建mapping")
@RequestMapping(value = "/createMapping",method = {RequestMethod.GET})
public Response createMapping(){
Response response = new Response();
try {
elasticsearchArticleService.createMapping();
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
@ApiOperation(value = "保存一篇文章",notes = "保存一篇文章")
@ApiImplicitParam(name = "articleInfo",value = "文章信息", required = true, dataType = "ArticleInfo")
@RequestMapping(value = "/save",method = {RequestMethod.GET,RequestMethod.POST})
public Response save(@ModelAttribute ArticleInfo articleInfo){
Response response = new Response();
try {
elasticsearchArticleService.saveArticle(articleInfo);
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
@ApiOperation(value = "根据ID查询一篇文章",notes = "根据ID查询一篇文章")
@ApiImplicitParam(name = "id",value = "文章id", required = true, dataType = "String")
@RequestMapping(value = "/findById",method = {RequestMethod.GET})
public Response findById(@RequestParam String id){
Response<ArticleInfo> response = new Response<>();
try {
ArticleInfo info = elasticsearchArticleService.findArticleInfoById(id);
response.setData(info);
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
@ApiOperation(value = "查询所有文章",notes = "查询所有文章")
@RequestMapping(value = "/findAll",method = {RequestMethod.GET})
public Response findAll(){
Response<List> response = new Response<>();
try {
List<ArticleInfo> list = elasticsearchArticleService.findAllArticle();
response.setData(list);
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
@ApiOperation(value = "根据关键字查询文章",notes = "根据关键字查询文章")
@ApiImplicitParam(name = "keyword",value = "关键字", required = true, dataType = "String")
@RequestMapping(value = "/findByKeyword",method = {RequestMethod.GET})
public Response findByKeyword(@RequestParam String keyword){
Response<List> response = new Response<>();
try {
List<ArticleInfo> list = elasticsearchArticleService.findArticleByKeyword(keyword);
response.setData(list);
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
@ApiOperation(value = "根据关键字查询文章(带分页)",notes = "根据关键字查询文章(带分页)")
@ApiImplicitParam(name = "keyword",value = "关键字", required = true, dataType = "String")
@RequestMapping(value = "/findByKeywordWithPage",method = {RequestMethod.GET})
public Response findByKeywordWithPage(@RequestParam("keyword") String keyword,
@RequestParam("pageNo") int pageNo,
@RequestParam("pageSize") int pageSize){
Response<Page> response = new Response<>();
try {
Page<ArticleInfo> list = elasticsearchArticleService.findArticleByKeywordWithPage(keyword,pageNo,pageSize);
response.setData(list);
} catch (Exception e){
response.setResult(false);
response.setMessage(e.getMessage());
}
return response;
}
}
8. 测试
- save
save
- findById
findById
- findByKeywordWithPage
findByKeywordWithPage
网友评论