Spring boot集成elasticsearch注解方式
安装IK分词
1.选择与es版本相同的IK下载源码,网站https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.4/elasticsearch-analysis-ik-6.2.4.zip
或者直接在git上面查找:https://github.com/medcl/elasticsearch-analysis-ik/releases
2,将解压好的ik复制到es的plugins目录下
安装head插件
1.head插件下载地址,https://github.com/mobz/elasticsearch-head
解压到任意目录,但是要和elasticsearch的安装目录区分开,也可以像笔者一样
创建一个叫article的实体类,其中的注解代表的含义分别是:
@Document: 代表一个文档记录 ,indexName: 用来指定索引名称, type: 用来指定索引类型
@Id: 用来将对象中id和ES中_id映射
@Field: 用来指定ES中的字段对应Mapping,其中的type: 用来指定ES中存储类型,analyzer: 用来指定使用哪种分词器
@Data @Document(indexName = "test-search",type = "article",shards = 1,replicas = 0, refreshInterval = "-1") public class Article implements Serializable { @Id private Long id; @Field(type = FieldType.Text,analyzer = "ik_max_word", searchAnalyzer = "ik_max_word") private String title; //标题 @Field(type = FieldType.Text,analyzer = "ik_max_word", searchAnalyzer = "ik_max_word") private String content;// 缩略内容 }
dao层,创建一个ArticleRepository的接口,继承ElasticsearchRepository
public interface ArticleRepository extends ElasticsearchRepository{ /** * 使用jpa的一个好处就是你想联合title和content去搜索,它就会有方法出现,使用pageable分页 * @param title * @param content * @param pageable * @return */ Page findByTitleLikeOrContentLike(String title, String content, Pageable pageable); /** * 根据article的content内容去搜索,使用pageable份额有 * @param content * @param pageable * @return */ Page findByContentLike(String content, Pageable pageable); }
service层,
@Service public class ArticleService { @Autowired private ArticleRepository articleRepository; public void save(Article article){ articleRepository.save(article); } public Pagesearch(String title, String content, Pageable pageable){ return articleRepository.findByTitleLikeOrContentLike(title,content,pageable); } public Page search(String content,Pageable pageable){ return articleRepository.findByContentLike(content,pageable); } public Page findAll(Pageable pageable){ return articleRepository.findAll(pageable); } }
controller
@RestController public class ArticleController { @Autowired private ArticleRepository articleRepository; @Autowired private ArticleService articleService; //可以插入单条也可以多条 @RequestMapping("/articleSave") public String save(){ Listarticles = new ArrayList<>(); articles.add(new Article(System.currentTimeMillis(),"小米", "小米手机")); articles.add(new Article(System.currentTimeMillis(),"华为", "华为手机")); for(int i=0; i articles = articleService.search(title,content,pageable); return articles.toString(); } }
启动类加相关注解,不加不起作用
@SpringBootApplication //@EnableRabbit @ComponentScan({"com.example"}) @MapperScan("com.example") @EnableElasticsearchRepositories(basePackages = "com.example") public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } }