SpringBoot整合ElasticSearch实现CRUD,分页查询,特殊条件查询,高亮查询案例

本文详细介绍了如何使用SpringBoot框架整合Elasticsearch进行全文检索应用开发,从环境搭建到具体实现步骤,包括导入依赖、创建启动类、配置文件、实体类、DAO接口、Service接口及其实现类,再到测试文件的编写,最后通过实例演示了数据的增删查改等操作。
摘要由CSDN通过智能技术生成


Demo目录格式如下

在这里插入图片描述

1. 导入pom.xml坐标依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

2. SpringBoot 环境搭建

2.0 创建启动类

@SpringBootApplication
public class SpringBootRunner {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRunner.class,args);
    }
}

2.1 创建application.yml配置文件

spring:
  data:
    elasticsearch:
      cluster-nodes: 127.0.0.1:9300

2.2 创建实体类 ArticleDocument

package com.jwc.pojo;

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.FieldType;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 14:50
 */
@Document(indexName = "blog2",type = "article")
public class ArticleDocument {
    @Id
    private Long id;

    @Override
    public String toString() {
        return "ArticleDocument{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }

    private String title;
    private String content;
    ... GET AND SET ...
}

2.3 创建ArticleDao接口

public interface ArticleDao extends ElasticsearchRepository<ArticleDocument,Long> {
    /*
     * 根据Title查找
     * */
    List<ArticleDocument> findByTitle(String title);

    /*
     * 根据Title 和 content查找
     * */
    List<ArticleDocument> findByTitleAndContent(String title, String content, Pageable pageable);
}

2.4 创建ArticleService 接口

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 14:55
 */

public interface ArticleService {
    /*
     * 增加记录
     * */
    void addArticle(ArticleDocument articleDocument);

    /*
     * 查询所有
     * */
    Iterable<ArticleDocument> findAll();

    /*
     * 查询一条记录
     * */

    ArticleDocument findOne(Long id);

    /*
     * 修改记录
     * */
    void updateArticle(ArticleDocument articleDocument);

    /*
     * 删除数据
     * */
    void deleteArticle(Long id);


    /*
     * 根据Title查找
     * */
    List<ArticleDocument> findByTitle(String title);


    /*
     * 根据Title 和 content查找
     * */
    List<ArticleDocument> findByTitleAndContent(String title, String content, Pageable pageable);
}

2.5 创建 ArticleServiceImpl 实现类

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 14:56
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleDao articleDao;

    @Override
    public void addArticle(ArticleDocument articleDocument) {
        articleDao.save(articleDocument);
    }

    @Override
    public Iterable<ArticleDocument> findAll() {
        return articleDao.findAll();
    }

    @Override
    public ArticleDocument findOne(Long id) {
        Optional<ArticleDocument> allById = articleDao.findById(id);
        return allById.isPresent()?allById.get():null;

    }

    @Override
    public void updateArticle(ArticleDocument articleDocument) {
        articleDao.save(articleDocument);
    }

    @Override
    public void deleteArticle(Long id) {
        articleDao.deleteById(id);
    }

    @Override
    public List<ArticleDocument> findByTitle(String title) {
        return articleDao.findByTitle(title);
    }

    @Override
    public List<ArticleDocument> findByTitleAndContent(String title, String content, Pageable pageable) {
        return articleDao.findByTitleAndContent(title,content,pageable);
    }
}

2.6 创建测试文件TestSpringBootES

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 15:05
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootRunner.class)
public class TestSpringBootES {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    /*
     * 测试添加数据
     * */
    @Test
    public void testAddArticle() {
        ArticleDocument ac = new ArticleDocument();
        ac.setId(102L);
        ac.setTitle("一个基于Lucene的搜索服务器102");
        ac.setContent("一个分布式多用户能力的全文搜索引擎102");
        articleService.addArticle(ac);
    }


    /*
     * 测试查询所有数据
     * */
    @Test
    public void testFindAll() {
        Iterable<ArticleDocument> all = articleService.findAll();
        for (ArticleDocument articleDocument : all) {
            System.out.println(articleDocument);
        }
    }

    /*
     * 测试查询一条数据
     * */
    @Test
    public void testFindOne() {
        ArticleDocument ac = articleService.findOne(102L);
        System.out.println(ac);
    }

    /*
     * 测试修改一条数据
     * */
    @Test
    public void testUpdate() {
        ArticleDocument ac = articleService.findOne(100L);
        ac.setTitle("修改一条数据");
        ac.setContent("一个分布式多用户能力的全文搜索引擎102");
        articleService.updateArticle(ac);
    }

    /*
     * 测试删除一条数据
     * */
    @Test
    public void testDelete() {
        articleService.deleteArticle(102L);
    }

    /*
     * 定义特殊方法,根据title查询
     * */
    @Test
    public void testFindByTitle() {
        List<ArticleDocument> aList = articleService.findByTitle("修改");
        for (ArticleDocument articleDocument : aList) {
            System.out.println(articleDocument);
        }

    }

    /*
     * 定义特殊方法,根据title 和 content 分页查询
     * */
    @Test
    public void testFindByTitleAndContent() {
        Pageable pageable = PageRequest.of(0, 20, Sort.by(Sort.Order.asc("id")));
        List<ArticleDocument> aList = articleService.findByTitleAndContent("基于", "分布式", pageable);
        for (ArticleDocument articleDocument : aList) {
            System.out.println(articleDocument);
        }

    }

    /*
     * 高亮处理
     * */
    @Test
    public void searchArticleBySearchQuery() {
        for (int i = 0; i < 3; i++) {
            HighlightBuilder.Field field = new HighlightBuilder.Field("title").preTags("<font color='red'>").postTags("</font>").fragmentSize(250);
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder().withHighlightFields(field);
            nativeSearchQueryBuilder.withSort(new FieldSortBuilder("id").order(SortOrder.DESC));
            nativeSearchQueryBuilder.withPageable(PageRequest.of(i, 5));
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("title", "搜索"));
//            Page<Article> page = articleService.searchBySearchQuery(nativeSearchQueryBuilder.build());
//            List<Article> articles = page.getContent();
            elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), ArticleDocument.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    System.out.println("总条数==" + hits.getTotalHits());
                    Iterator<SearchHit> it = hits.iterator();
                    for (SearchHit hit : hits) {
                        Text[] titles = hit.getHighlightFields().get("title").fragments();
                        for (Text title : titles) {
                            System.out.println("title==" + title.string());
                        }
                    }
                    return null;
                }
            });
            System.out.println("=========分隔符========");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

叫我三胖哥哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值