ES-docker安装参考这篇: Centos7使用Docker部署Elasticsearch服务+IK分词器及Head插件安装
ES-windows安装参考这篇: windows10安装ElasticSearch与Head-master+IK分词器安装与自定义词库
pom.xml
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
application.yml
server:
port: 9001 #端口号
spring:
application:
name: sunmone-search #服务名称
data:
elasticsearch:
cluster-nodes: 192.168.1.158:9300 # ES服务地址
实体类
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/*
* @Document(indexName = "索引名称",type = "表名称")
* 如果索引不存在,那么将会自动创建索引,type同理
* */
@Document(indexName = "tensquare", type = "article")
public class Article implements Serializable {
@Id // @Id 让ES知道这个字段是_id
private String id;
// 字段开启分词,分词规则: 最细粒度切分,搜索规则:最细粒度搜索
@Field(index = true, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String title;
// 字段开启分词,分词规则: 最细粒度切分,搜索规则:最细粒度搜索
@Field(index = true, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String content;
private String state;
... GET AND SET ...
}
启动类
@SpringBootApplication
public class SearchApplication {
public static void main(String[] args) {
SpringApplication.run(SearchApplication.class);
}
}
// SpringBoot使用ES,继承 ElasticsearchRepository <实体类,主键ID类型>
public interface ArticleDao extends ElasticsearchRepository<Article, String> {
// 按关键词分页查询
public Page<Article> findByTitleLikeOrContentLike(String title, String content, Pageable pageable);
}
@Service
public class ArticleService {
@Autowired
private ArticleDao articleDao;
// 按关键词分页查询
public Page<Article> search(String keywords, int page, int size) {
PageRequest pageRequest = PageRequest.of(page - 1, size);
return articleDao.findByTitleLikeOrContentLike(keywords, keywords, pageRequest);
}
// 添加数据 以下语法跟mysql一致
public void save(Article article) {
// 这里记得设置ID,我用的工具类雪花ID
article.setId("1");
articleDao.save(article);
}
// 修改
public void update(Article article) {
articleDao.save(article);
}
// 删除
public void deleteById(String id) {
articleDao.deleteById(id);
}
// 按ID查询
public Article findById(String id) {
return articleDao.findById(id).get();
}
}
@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
// 添加数据
@RequestMapping(method = RequestMethod.POST)
public Result save(@RequestBody Article article) {
articleService.save(article);
return new Result(true, StatusCode.OK, "添加成功");
}
// 关键词分页查询
@RequestMapping(value = "search/{keywords}/{page}/{size}", method = RequestMethod.GET)
public Result search(@PathVariable String keywords, @PathVariable int page, @PathVariable int size) {
Page<Article> search = articleService.search(keywords, page, size);
return new Result(true, StatusCode.OK, "查询成功",
new PageResult(search.getTotalElements(), search.getContent()));
}
}
我手动添加了几条数据