ElasticSearch-使用SpringDataElasticSearch完成增删改查,分页查询,特殊条件查询,高亮查询案例

文章目录

    • 1. 导入pom.xml坐标依赖
    • 2. SpringBoot 环境搭建
      • 2.0 创建启动类
      • 2.1 创建application.yml配置文件
      • 2.2 创建实体类 ArticleDocument
      • 2.3 创建ArticleDao接口
      • 2.4 创建ArticleService 接口
      • 2.5 创建 ArticleServiceImpl 实现类
      • 2.6 创建测试文件TestSpringBootES

Demo目录格式如下

ElasticSearch-使用SpringDataElasticSearch完成增删改查,分页查询,特殊条件查询,高亮查询案例_第1张图片

1. 导入pom.xml坐标依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.9.4version>
        dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.4version>
        dependency>
    dependencies>

2. SpringBoot 环境搭建

2.0 创建启动类

package com.jwc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 14:34
 */
@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;

    public Long getId() {
     
        return id;
    }

    public void setId(Long id) {
     
        this.id = id;
    }

    public String getTitle() {
     
        return title;
    }

    public void setTitle(String title) {
     
        this.title = title;
    }

    public String getContent() {
     
        return content;
    }

    public void setContent(String content) {
     
        this.content = content;
    }
}

2.3 创建ArticleDao接口

package com.jwc.dao;

import com.jwc.pojo.ArticleDocument;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-07-31 14:54
 */
/*
* 接口定义
* */
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 接口

package com.jwc.service;

import com.jwc.pojo.ArticleDocument;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ 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 实现类

package com.jwc.service.impl;

import com.jwc.dao.ArticleDao;
import com.jwc.pojo.ArticleDocument;
import com.jwc.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @ 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

package com.jwc.test;

import com.jwc.SpringBootRunner;
import com.jwc.pojo.ArticleDocument;
import com.jwc.service.ArticleService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;



import java.util.Iterator;
import java.util.List;

/**
 * @ 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("").postTags("").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
page = articleService.searchBySearchQuery(nativeSearchQueryBuilder.build()); // List
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("=========分隔符========"); } } }

你可能感兴趣的:(java,elasticsearch,搜索引擎,java,spring,boot)