SpringBoot集成Elasticsearch(三)——ElasticSearchRestTemplate类与ElasticsearchRepository类

时间:2025-05-12 09:41:42

SpringBoot集成Elasticsearch系列文章目录

SpringBoot集成Elasticsearch(一)——索引库创建等
SpringBoot集成Elasticsearch(二)——文档管理等
SpringBoot集成Elasticsearch(三)——ElasticSearchRestTemplate类与ElasticsearchRepository类


文章目录

  • SpringBoot集成Elasticsearch系列文章目录
  • 一、使用ElasticsearchRestTemplate类
    • 1.创建索引库
    • 2.创建索引库并实体类设置mapping
    • 3.删除索引库
    • 4.索引库查询
  • 二.使用ElasticsearchRepository类
    • 1.创建接口继承ElasticsearchRepository
    • 2.使用BlogRepository接口
  • 总结


SpringData对ES的封装ElasticsearchRestTemplate类,可直接使用,此类在ElasticsearchRestTemplate基础上进行性一定程度的封装,使用起来更方便灵活,拓展性更强。ElasticsearchRepository可以被继承操作ES,是SpringBoot对ES的高度封装,操作最为方便,但牺牲了灵活性。
索引库实体类
@Data
@Document(indexName = "blog_1", shards = 5, replicas = 1)
public class Blog {
    @Field(type = FieldType.Long, store = true)
    private Long id;
    
    //type =      字段类型为text
    //analyzer = "ik_max_word"  分词器为"ik_max_word"
    //store = true              存储 => 是
    @Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
    private String title;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
    private String content;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
    private String comment;

    @Field(type = FieldType.Keyword, store = true)
    private String mobile;

}

一、使用ElasticsearchRestTemplate类

1.创建索引库

@Autowired
private ElasticsearchRestTemplate template;
	/**
	* 创建索引库
	*/
	public void createIndex(){
	   //创建索引库
	   template. indexOps(IndexCoordinates.of("mytest")).create();
    }

2.创建索引库并实体类设置mapping

1)创建索引库
((“mytest”)).create();
2)设置mapping信息
需要创建一个实体类,其中配置实体类和文档的映射关系,使用注解配置。
可以从Entity中生成mapping信息。

public void putMapping(){
     //创建索引库
     Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);
     template.indexOps(IndexCoordinates.of("mytest")).putMapping(mapping);
}

3.删除索引库

	//删除索引库
    public void deleteIndex(){
        template.indexOps(IndexCoordinates.of("hello1")).delete();
    }

4.索引库查询

public void maxQueryTest(){
        NativeSearchQuery builder = new NativeSearchQueryBuilder()
                //多字段查询  (高亮跟查询条件有关)
                .withQuery(QueryBuilders.multiMatchQuery("8", "id","title"))
                //增加过滤条件, 可以设置多个
                .withFilter(QueryBuilders.boolQuery()
                        //增加bool查询:should的term关键字查询
                        .should(QueryBuilders.termQuery("title", "文章"))
                        .should(QueryBuilders.termQuery("content","xxx"))
                )
                //增加过滤条件的关键字查询
                .withFilter(QueryBuilders.termQuery("mobile", "13344556677"))
                //分页设置
                .withPageable(PageRequest.of(0,5))
                //设置高亮
                .withHighlightBuilder(new HighlightBuilder()
                        //高亮显示的字段
                        .field("title")
                        //高亮显示的字段
                        .field("content")
                        //高亮显示的前缀
                        .preTags("<em>")
                        //高亮显示的后缀
                        .postTags("</em>")
                )
                //添加聚合查询
                .addAggregation(new TermsAggregationBuilder("mobile_group").field("mobile"))
                .build();

        //基于 类型返回的结果
        SearchHits<Blog> searchHits = template.search(builder, Blog.class);

        //从searchHits取相关数据
        long totalHits = searchHits.getTotalHits();               //取总记录数
        List<SearchHit<Blog>> list = searchHits.getSearchHits();  //取每条数据放入集合中
        System.out.println("总记录数为:" + totalHits);
        list.forEach(blogSearchHit -> {
            //取原生文档对象
            Blog blog = blogSearchHit.getContent();
            System.out.println(blog);
            //取高亮对象
            Map<String, List<String>> highlightFields = blogSearchHit.getHighlightFields();
            System.out.println(highlightFields);

            //取高亮对象 放到Blog里去 这样就将Blog和高亮结合输出了
            String title = highlightFields.get("title").get(0);
            //String content = ("content").get(0);
            blog.setTitle(title);
            //(content);
            System.out.println(blog);
        });

        //取聚合结果
        Aggregations aggregations = searchHits.getAggregations();
        System.out.println(aggregations.toString());
    }

二.使用ElasticsearchRepository类

1.创建接口继承ElasticsearchRepository

public interface BlogRepository extends ElasticsearchRepository<Blog, Long> {
    /**
     * 定义一个方法查询:根据title查询es
     *
     * 原因:  ElasticsearchRepository会分析方法名,参数对应es中的field(这就是灵活之处)
     * @param title
     * @return <>
     */
    List<Blog> findByTitle(String title);

	/**
     * 定义一个方法查询: 根据title,content查询es
     */
    List<Blog> findByTitleAndContent(String title, String content);

}

2.使用BlogRepository接口

public class BlogRepositoryTest {

    @Autowired
    private BlogRepository blogRepository;

    /**
     * 添加文档
     */
    @Test
    public void addDocument(){
        Blog blog = new Blog();
        for (int i = 0; i < 10; i++) {
            blog.setId((long)i+1);
            blog.setTitle("测试spring集成es"+i+1);
            blog.setContent("sjihfapf"+i+1);
            blog.setComment("注释内容"+i+1);
            blog.setMobile("12345678901");
            blogRepository.save(blog);
        }
    }

    /**
     * 更新文档
     */
    @Test
    public void updateDocument(){
        Optional<Blog> optional = blogRepository.findById(1l);
        if (optional.isPresent()){
            Blog blog = optional.get();
            blog.setTitle("hello update");
            blogRepository.save(blog);
        }
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteDocument() {
        blogRepository.deleteById(1l);
    }


    /**
     * 查询所有 文档
     */
    @Test
    public void getDocument() {
        //根据id查找
        //Optional<Blog> optional = (1l);
        //Blog blog = ();
        //(blog);

        //查找全部
        //Iterable<Blog> all = ();
        //(blog -> (blog));

        //分页查找全部
        Iterable<Blog> all = blogRepository.findAll(PageRequest.of(1,10));
        all.forEach(blog -> System.out.println(blog));
    }


	/**
     * 自定义方法:根据title内容查询索引库
     * /
    @Test
    public void testFindByTitle(){
        List<Blog> blogList = ("测试");
        ().forEach(::println);
    }

	/**
     * 自定义方法:根据title,content内容查询索引库
     * /
    @Test
    public void testFindByTitleAndContent(){
        List<Blog> blogList = ("测试", "sjihfapf");
        ().forEach(::println);
    }
}

}

总结

以上就是SpringBoot对ES客户端封装类的相关操作内容,有兴趣同学的可以继续深入学习。