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

SpringBoot集成Elasticsearch系列文章目录

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



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 = FieldType.Text     字段类型为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)创建索引库
template.indexOps(IndexCoordinates.of(“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();

        //基于Blog.class 类型返回的结果
        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 = highlightFields.get("content").get(0);
            blog.setTitle(title);
            //blog.setContent(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 java.util.List<com.yt.cubemall.search.model.Blog>
     */
    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 = blogRepository.findById(1l);
        //Blog blog = optional.get();
        //System.out.println(blog);

        //查找全部
        //Iterable<Blog> all = blogRepository.findAll();
        //all.forEach(blog -> System.out.println(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 = blogRepository.findByTitle("测试");
        blogList.stream().forEach(System.out::println);
    }

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

}

总结

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

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot中使用Elasticsearch进行分页查询,可以通过继承ElasticsearchRepository接口来实现。首先,确保已经引入了spring-boot-starter-data-elasticsearch依赖,并配置好相关的Elasticsearch连接信息。 接下来,创建一个继承自ElasticsearchRepository的接口,并指定实体和主键型。在该接口中,可以使用Spring Data Elasticsearch提供的方法进行分页查询,其中包括searchSimilar方法。 下面是一个示例代码: ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface UserRepository extends ElasticsearchRepository<User, String> { @Query("{\"bool\" : {\"must\" : {\"term\" : {\"name\" : \"?0\"}}}}") Page<User> searchSimilar(String name, Pageable pageable); } ``` 在上述示例中,User是实体,String是主键型。searchSimilar方法使用了自定义的查询语句,并通过Pageable参数实现了分页查询。 使用该接口进行分页查询的示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public Page<User> searchSimilarUsers(String name, int page, int size) { Pageable pageable = PageRequest.of(page, size); return userRepository.searchSimilar(name, pageable); } } ``` 在上述示例中,UserService使用了UserRepository接口进行分页查询,通过调用searchSimilar方法实现了根据name字段进行相似查询,并指定了页码和每页大小。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冉木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值