SpringBoot整合Elasticsearch与综合实例(二):搜索、分页、排序

Elasticsearch 是一个分布式、可扩展、近实时的高性能搜索与数据分析引擎。Elasticsearch 基于 Apache Lucene 构建,采用 Java 编写,并使用 Lucene 构建索引、提供搜索功能。Elasticsearch 的目标是让全文搜索功能的落地变得简单。

本文是SpringBoot整合Elasticsearch与综合实例的第二篇,主要实现SpringBoot整合Elasticsearch实现搜索、分页、排序的相关操作。

SpringBoot整合Elasticsearch与综合实例系列:

《SpringBoot整合Elasticsearch与综合实例(一):索引、文档》

《SpringBoot整合Elasticsearch与综合实例(二):搜索、分页、排序》

1、SpringBoot整合Elasticsearch的步骤

 

(1)创建SpringBoot项目,项目结构如下图:

(2)使用Maven添加依赖文件

在pom.xml配置信息文件中,添加 Elasticsearch服务、Elasticsearch高级客户端的依赖:

 

<!-- Elasticsearch服务 -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.11.1</version>
</dependency>
 
<!-- Elasticsearch高级客户端 -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.11.1</version>
</dependency>

(3)Elasticsearch的配置

 

在 application.yml 配置文件中配置 Elasticsearch 信息:

# Elasticsearch配置
elasticsearch:
  hostname: 127.0.0.1
  port: 9200
  scheme: http

(4)Elasticsearch配置类(config层)

创建 com.pjb.config 包,并创建 ElasticsearchConfig 类(Elasticsearch配置类),并使用 @Configuration 注解,标注该类为配置类。

package com.pjb.config;
 
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * Elasticsearch配置类
 * @author pan_junbiao
 **/
@Configuration
public class ElasticsearchConfig
{
    @Value("${elasticsearch.hostname}")
    private String hostname;
 
    @Value("${elasticsearch.port}")
    private int port;
 
    @Value("${elasticsearch.scheme}")
    private String scheme;
 
    /**
     * 初始化:高级客户端
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient()
    {
        RestHighLevelClient restHighLevelClient = null;
        try
        {
            RestClientBuilder builder = RestClient.builder(new HttpHost(hostname, port, scheme));
            restHighLevelClient = new RestHighLevelClient(builder);
            return restHighLevelClient;
        }
        catch (Exception ex)
        {
            System.out.println("初始化Elasticsearch高级客户端失败");
            ex.printStackTrace();
        }
        return restHighLevelClient;
    }
}

2、搜索操作

Elasticsearch 是面向文档的,它可存储整个文档。但 Elasticsearch 对文档的操作不仅限于存储,Elasticsearch 还会索引每个文档的内容使之可以被搜索。

在 Elasticsearch 中,用户可以对文档数据进行索引、搜索、排序和过滤等操作,而这也是 Elasticsearch 能够执行复杂的全文搜索的原因之一。

【实例】SpringBoot整合Elasticsearch,并实现搜索、分页、排序。

实例要求:

1、实现 Elasticsearch 搜索数据,并进行分页、排序。

2、实现 Elasticsearch 按查询条件获取数据。

3、实现 Elasticsearch 按按照区间范围搜索(按照:博客积分范围进行搜索)。

执行结果如下图:

定义一个博客信息(blog_info)的数据表结构:

 

字段类型说明
blogIdlong博客ID
blogNametext博客名称
blogUrlkeyword博客地址
blogPointsdouble博客积分
createDatedate创建时间
blogDescribetext博客描述

(1)编写实体类(Entity层)

(1)编写实体类(Entity)

创建 com.pjb.entity 包,并创建BlogInfo类(博客信息实体类)。

package com.pjb.entity;
 
import java.util.Date;
 
/**
 * 博客信息实体类
 * @author pan_junbiao
 **/
public class BlogInfo
{
    private int blogId; //博客ID
    private String blogName; //博客名称
    private String blogUrl; //博客地址
    private double blogPoints; //博客积分
    private Date createDate; //创建时间
    private String blogDescribe; //博客描述
 
    //构建方法1
    public BlogInfo()
    {
    }
 
    //构建方法2
    public BlogInfo(int blogId, String blogName, String blogUrl, double blogPoints, Date createDate, String blogDescribe)
    {
        this.blogId = blogId;
        this.blogName = blogName;
        this.blogUrl = blogUrl;
        this.blogPoints = blogPoints;
        this.createDate = createDate;
        this.blogDescribe = blogDescribe;
    }
 
    public int getBlogId()
    {
        return blogId;
    }
 
    public void setBlogId(int blogId)
    {
        this.blogId = blogId;
    }
 
    public String getBlogName()
    {
        return blogName;
    }
 
    public void setBlogName(String blogName)
    {
        this.blogName = blogName;
    }
 
    public String getBlogUrl()
    {
        return blogUrl;
    }
 
    public void setBlogUrl(String blogUrl)
    {
        this.blogUrl = blogUrl;
    }
 
    public double getBlogPoints()
    {
        return blogPoints;
    }
 
    public void setBlogPoints(double blogPoints)
    {
        this.blogPoints = blogPoints;
    }
 
    public Date getCreateDate()
    {
        return createDate;
    }
 
    public void setCreateDate(Date createDate)
    {
        this.createDate = createDate;
    }
 
    public String getBlogDescribe()
    {
        return blogDescribe;
    }
 
    public void setBlogDescribe(String blogDescribe)
    {
        this.blogDescribe = blogDescribe;
    }
}

创建公共分页类(BasePaging.java)。

package com.pjb.entity.page;
 
/**
 * 公共分页类
 * @author pan_junbiao
 **/
public class BasePaging
{
    private int pageIndex; //当前页码
    private int pageSize; //分页大小
    private int totalData; //数据总数
    private int totalPage; //总页数
    private String orderBy; //排序
    private int offset; //偏移量
    private String indexName; //索引名称
 
    public int getPageIndex()
    {
        return pageIndex;
    }
 
    public void setPageIndex(int pageIndex)
    {
        this.pageIndex = pageIndex;
    }
 
    public int getPageSize()
    {
        return pageSize;
    }
 
    public void setPageSize(int pageSize)
    {
        this.pageSize = pageSize;
    }
 
    public int getTotalData()
    {
        return totalData;
    }
 
    public void setTotalData(int totalData)
    {
        this.totalData = totalData;
    }
 
    public String getOrderBy()
    {
        return orderBy;
    }
 
    public void setOrderBy(String orderBy)
    {
        this.orderBy = orderBy;
    }
 
    //计算偏移量:偏移量 = (page_index-1)*page_size
    public int getOffset()
    {
        int offset = 0;
        if(this.pageIndex>0 && this.pageSize>0)
        {
            offset = (this.pageIndex-1)*this.pageSize;
        }
        return offset;
    }
 
    //计算总页数:总页数 = (数据总数 + 分页大小 -1) / 分页大小
    public int getTotalPage()
    {
        int totalPage = 0;
        if (this.totalData > 0 && this.pageSize > 0)
        {
            totalPage = (this.totalData + this.pageSize - 1) / this.pageSize;
        }
        return totalPage;
    }
 
    public String getIndexName()
    {
        return indexName;
    }
 
    public void setIndexName(String indexName)
    {
        this.indexName = indexName;
    }
}

创建分页结果类(PageResult.java),并继承公共分页类(BasePaging.java)。

package com.pjb.entity.page;
 
import java.util.List;
 
/**
 * 分页结果类
 * @author pan_junbiao
 **/
public class PageResult<T> extends BasePaging
{
    private List<T> dataList; //数据列表
 
    public List<T> getDataList()
    {
        return dataList;
    }
 
    public void setDataList(List<T> dataList)
    {
        this.dataList = dataList;
    }
}

创建博客搜索参数类(BlogSearchParam.java),并继承公共分页类(BasePaging.java)。

package com.pjb.entity.param;
 
import com.pjb.entity.page.BasePaging;
 
/**
 * 博客搜索参数类
 * @author pan_junbiao
 **/
public class BlogSearchParam extends BasePaging
{
    private String blogDescribe; //博客描述
    private double pointsBegin; //开始博客积分
    private double pointsEnd; //结束博客积分
 
    public String getBlogDescribe()
    {
        return blogDescribe;
    }
 
    public void setBlogDescribe(String blogDescribe)
    {
        this.blogDescribe = blogDescribe;
    }
 
    public double getPointsBegin()
    {
        return pointsBegin;
    }
 
    public void setPointsBegin(double pointsBegin)
    {
        this.pointsBegin = pointsBegin;
    }
 
    public double getPointsEnd()
    {
        return pointsEnd;
    }
 
    public void setPointsEnd(double pointsEnd)
    {
        this.pointsEnd = pointsEnd;
    }
}

(2)实现业务逻辑层(Service层)

创建博客业务逻辑接口(BlogService.java)。

package com.pjb.service.impl;
 
import com.pjb.entity.BlogInfo;
import com.pjb.entity.page.PageResult;
import com.pjb.entity.param.BlogSearchParam;
 
import java.util.List;
 
/**
 * 博客业务逻辑接口
 * @author pan_junbiao
 **/
public interface BlogService
{
    //====================================搜索操作==================================
 
    /**
     * 分页搜索列表
     */
    public PageResult<BlogInfo> searchBlogListPage(BlogSearchParam param);
}

创建用户信息业务逻辑类(UserServiceImpl.java),并实现UserService接口,编写业务逻辑方法。

package com.pjb.service;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjb.entity.BlogInfo;
import com.pjb.entity.page.PageResult;
import com.pjb.entity.param.BlogSearchParam;
import com.pjb.service.impl.BlogService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
/**
 * 博客业务逻辑类
 * @author pan_junbiao
 **/
@Service
public class BlogServiceImpl implements BlogService
{
    /**
     * Elasticsearch高级客户端
     */
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    
    //====================================搜索操作==================================
 
    /**
     * 分页搜索列表
     */
    @Override
    public PageResult<BlogInfo> searchBlogListPage(BlogSearchParam param)
    {
        PageResult<BlogInfo> blogInfoPageResult = new PageResult<>();
        List<BlogInfo> blogInfoList = new ArrayList<>();
        blogInfoPageResult.setDataList(blogInfoList);
 
        //参数验证
        if(param.getIndexName() ==null || param.getIndexName().length()<=0)
        {
            return blogInfoPageResult;
        }
 
        try
        {
            //1、构建搜索请求
            SearchRequest searchRequest = new SearchRequest(param.getIndexName());
 
            //大多数搜索参数都添加到 SearchSourceBuilder 类中
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
 
            //设置“全部匹配”查询
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
 
            //设置分页条件
            searchSourceBuilder.from(param.getOffset()).size(param.getPageSize());
 
            //查询条件1:博客描述
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();
            if(param.getBlogDescribe()!=null && param.getBlogDescribe().length()>0)
            {
                MatchPhraseQueryBuilder mpq1 = QueryBuilders.matchPhraseQuery("blogDescribe", param.getBlogDescribe());
                ((BoolQueryBuilder) queryBuilder).must(mpq1);
            }
 
            //查询条件2:根据博客积分区间范围
            RangeQueryBuilder mpq2 = QueryBuilders.rangeQuery("blogPoints");
            if(param.getPointsBegin()>0)
            {
                mpq2.from(param.getPointsBegin());
            }
            if(param.getPointsEnd()>0)
            {
                mpq2.to(param.getPointsEnd());
            }
            ((BoolQueryBuilder) queryBuilder).must(mpq2);
 
            //将多个查询条件组合
            searchSourceBuilder.query(queryBuilder);
 
            //设置排序,注意:在ES中,只有keyword类型的字符串可以排序、分组聚合
            searchSourceBuilder.sort(new FieldSortBuilder("blogPoints").order(SortOrder.DESC));
            searchSourceBuilder.sort(new FieldSortBuilder("createDate").order(SortOrder.ASC));
 
            //设置一个可选的超时时间,控制允许搜索的时间
            searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
            //将 SearchSourceBuilder 添加到 SearchRequest 中
            searchRequest.source(searchSourceBuilder);
 
            //2、执行搜索请求,获取响应结果
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
 
            //3、解析搜索请求的响应结果
            System.out.println("响应结果:" + searchResponse);
            //获取HTTP状态码
            RestStatus status = searchResponse.status();
            System.out.println("HTTP状态码:" + status);
 
            //获取请求执行时间
            TimeValue took = searchResponse.getTook();
            System.out.println("请求执行时间:" + took);
 
            //获取请求是否超时
            boolean timedOut = searchResponse.isTimedOut();
            System.out.println("请求是否超时:" + timedOut);
 
            //查看搜索影响的分片总数
            int totalShards = searchResponse.getTotalShards();
            System.out.println("查看搜索影响的分片总数:" + totalShards);
 
            //执行搜索成功的分片的统计信息
            int successfulShards = searchResponse.getSuccessfulShards();
            System.out.println("执行搜索成功的分片的统计信息:" + successfulShards);
 
            //执行搜索失败的分片的统计信息
            int failedShards = searchResponse.getFailedShards();
            System.out.println("执行搜索失败的分片的统计信息:" + failedShards);
 
            //遍历错误信息
            for(ShardSearchFailure failure : searchResponse.getShardFailures())
            {
                System.out.println("错误信息:" + failure.toString());
            }
 
            //获取响应中包含的搜索结果
            SearchHits hits = searchResponse.getHits();
 
            //SearchHits提供了相关结果的全部信息,如:点击总数、最高分数
            TotalHits totalHits = hits.getTotalHits();
 
            //搜索结果的总数量
            long total = totalHits.value;
            System.out.println("搜索结果的总数量:" + total);
 
            //点击总数
            long numHits = totalHits.value;
            System.out.println("点击总数:" + numHits);
 
            //最高分数
            float maxScore = hits.getMaxScore();
            System.out.println("最高分数:" + maxScore);
 
            //嵌套在 SearchHits 中的是可以迭代的单个搜索结果
            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit : searchHits)
            {
                String index = hit.getIndex(); //索引
                String id = hit.getId(); //文档ID
                float score = hit.getScore(); //每次搜索的得分
                System.out.println("索引:" + index + ",文档ID:" + id + ",每次搜索的得分:" + score);
 
                //以JSON字符串形式返回文档源
                String sourceAsString = hit.getSourceAsString();
                System.out.println("以JSON字符串形式返回文档源:" + sourceAsString);
 
                //以键值对形式返回文档源
                Map<String,Object> sourceAsMap = hit.getSourceAsMap();
                System.out.println("以键值对形式返回文档源:" + sourceAsMap.toString());
 
                //使用Jackson工具,将JSON转换为实体类
                ObjectMapper mapper = new ObjectMapper();
                BlogInfo blogInfo = mapper.readValue(sourceAsString, BlogInfo.class);
                blogInfoList.add(blogInfo);
            }
 
            //4、封装分页搜索结果类
            blogInfoPageResult.setDataList(blogInfoList); //数据列表
            blogInfoPageResult.setPageIndex(param.getPageIndex()); //当前页码
            blogInfoPageResult.setPageSize(param.getPageSize()); //分页大小
            blogInfoPageResult.setTotalData((int)total);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
 
        return blogInfoPageResult;
    }
}

2.1 搜索

//查询条件1:博客描述
QueryBuilder queryBuilder = QueryBuilders.boolQuery();
if(param.getBlogDescribe()!=null && param.getBlogDescribe().length()>0)
{
    MatchPhraseQueryBuilder mpq1 = QueryBuilders.matchPhraseQuery("blogDescribe", param.getBlogDescribe());
    ((BoolQueryBuilder) queryBuilder).must(mpq1);
}
 
//查询条件2:根据博客积分区间范围
RangeQueryBuilder mpq2 = QueryBuilders.rangeQuery("blogPoints");
if(param.getPointsBegin()>0)
{
    mpq2.from(param.getPointsBegin());
}
if(param.getPointsEnd()>0)
{
    mpq2.to(param.getPointsEnd());
}
((BoolQueryBuilder) queryBuilder).must(mpq2);
 
//将多个查询条件组合
searchSourceBuilder.query(queryBuilder);

2.2 分页

//设置分页条件
searchSourceBuilder.from(param.getOffset()).size(param.getPageSize());

2.3 排序

//设置排序,注意:在ES中,只有keyword类型的字符串可以排序、分组聚合
searchSourceBuilder.sort(new FieldSortBuilder("blogPoints").order(SortOrder.DESC));
searchSourceBuilder.sort(new FieldSortBuilder("createDate").order(SortOrder.ASC));

3、综合实例

编写测试方法(Test层)

创建BlogServiceTest类(博客服务测试类)。

package com.pjb;
 
import com.pjb.entity.BlogInfo;
import com.pjb.entity.page.PageResult;
import com.pjb.entity.param.BlogSearchParam;
import com.pjb.service.impl.BlogService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * 博客服务测试类
 * @author pan_junbiao
 **/
@SpringBootTest
public class BlogServiceTest
{
    @BeforeEach
    private void setUp()
    {
    }
 
    @AfterEach
    private void tearDown()
    {
    }
 
    /**
     * 博客业务逻辑类
     */
    @Autowired
    private BlogService blogService;
 
    /**
     * 索引名称
     * 注意:索引名称必须小写
     */
    private String _indexName = "blog_info";
 
    //====================================搜索操作==================================
 
    /**
     * 测试:批量新增文档
     * @author pan_junbiao
     */
    @Test
    public void addBulkDocument()
    {
        //创建博客实体列表
        List<BlogInfo> blogInfoList = new ArrayList<>();
        blogInfoList.add(new BlogInfo(1,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",120.68,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(2,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",85.12,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(3,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",94.37,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(4,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",365.19,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(5,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",287.33,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(6,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",355.28,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(7,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",48.13,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(8,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",864.86,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(9,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",685.46,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(10,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",97.75,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(11,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",543.18,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
        blogInfoList.add(new BlogInfo(12,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",256.39,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
 
        //批量新增文档
        boolean result = blogService.addBulkDocument(_indexName, blogInfoList);
        if(result)
        {
            System.out.println("批量新增文档成功");
        }
        else
        {
            System.out.println("批量新增文档失败");
        }
    }
 
    /**
     * 测试:分页搜索列表,按条件搜索
     * @author pan_junbiao
     */
    @Test
    public void searchBlogListPage()
    {
        //设置搜索条件
        BlogSearchParam blogSearchParam = new BlogSearchParam();
        blogSearchParam.setBlogDescribe("博客");
        blogSearchParam.setIndexName(_indexName);
        blogSearchParam.setPageIndex(1); //获取第1页数据
        blogSearchParam.setPageSize(5); //每页5条数据
 
        //执行分页搜索列表
        PageResult<BlogInfo> blogInfoPageResult = blogService.searchBlogListPage(blogSearchParam);
 
        //获取博客列表
        List<BlogInfo> blogList = blogInfoPageResult.getDataList();
        if (blogList != null && blogList.size()>0)
        {
            for(BlogInfo blog : blogList)
            {
                System.out.println("编号:" + blog.getBlogId() +" 名称:" + blog.getBlogName() + " 积分:" + blog.getBlogPoints() + " " + blog.getBlogUrl()+ " " + blog.getBlogDescribe());
            }
        }
        //分页信息
        System.out.println("当前页码:第" + blogInfoPageResult.getPageIndex()+"页");
        System.out.println("分页大小:每页" + blogInfoPageResult.getPageSize()+"条");
        System.out.println("数据总数:共" + blogInfoPageResult.getTotalData()+"条");
        System.out.println("总页数:共" + blogInfoPageResult.getTotalPage()+"页");
    }
 
    /**
     * 测试:分页搜索列表,按区间范围搜索
     * @author pan_junbiao
     */
    @Test
    public void searchBlogListPageByRange()
    {
        //设置搜索条件
        BlogSearchParam blogSearchParam = new BlogSearchParam();
        blogSearchParam.setBlogDescribe("博客");
        blogSearchParam.setIndexName(_indexName);
        blogSearchParam.setPageIndex(1); //获取第1页数据
        blogSearchParam.setPageSize(5); //每页5条数据
 
        //设置博客积分区间范围
        blogSearchParam.setPointsBegin(100);
        blogSearchParam.setPointsEnd(500);
 
        //执行分页搜索列表
        PageResult<BlogInfo> blogInfoPageResult = blogService.searchBlogListPage(blogSearchParam);
 
        //获取博客列表
        List<BlogInfo> blogList = blogInfoPageResult.getDataList();
        if (blogList != null && blogList.size()>0)
        {
            for(BlogInfo blog : blogList)
            {
                System.out.println("编号:" + blog.getBlogId() +" 名称:" + blog.getBlogName() + " 积分:" + blog.getBlogPoints() + " " + blog.getBlogUrl()+ " " + blog.getBlogDescribe());
            }
        }
        //分页信息
        System.out.println("当前页码:第" + blogInfoPageResult.getPageIndex()+"页");
        System.out.println("分页大小:每页" + blogInfoPageResult.getPageSize()+"条");
        System.out.println("数据总数:共" + blogInfoPageResult.getTotalData()+"条");
        System.out.println("总页数:共" + blogInfoPageResult.getTotalPage()+"页");
    }
}

3.1 批量新增文档

批量新增12条文档数据,用于测试使用。

/**
 * 测试:批量新增文档
 * @author pan_junbiao
 */
@Test
public void addBulkDocument2()
{
    //创建博客实体列表
    List<BlogInfo> blogInfoList = new ArrayList<>();
    blogInfoList.add(new BlogInfo(1,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",120.68,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(2,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",85.12,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(3,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",94.37,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(4,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",365.19,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(5,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",287.33,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(6,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",355.28,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(7,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",48.13,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(8,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",864.86,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(9,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",685.46,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(10,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",97.75,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(11,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",543.18,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
    blogInfoList.add(new BlogInfo(12,"pan_junbiao的博客","https://blog.csdn.net/pan_junbiao",256.39,new Date(),"您好,欢迎访问 pan_junbiao的博客"));
 
    //批量新增文档
    boolean result = blogService.addBulkDocument(_indexName, blogInfoList);
    if(result)
    {
        System.out.println("批量新增文档成功");
    }
    else
    {
        System.out.println("批量新增文档失败");
    }
}

使用 ElasticSearch-head 插件查看执行结果:

3.2 分页搜索

/**
 * 测试:分页搜索列表,按条件搜索
 * @author pan_junbiao
 */
@Test
public void searchBlogListPage()
{
    //设置搜索条件
    BlogSearchParam blogSearchParam = new BlogSearchParam();
    blogSearchParam.setBlogDescribe("博客");
    blogSearchParam.setIndexName(_indexName);
    blogSearchParam.setPageIndex(1); //获取第1页数据
    blogSearchParam.setPageSize(5); //每页5条数据
 
    //执行分页搜索列表
    PageResult<BlogInfo> blogInfoPageResult = blogService.searchBlogListPage(blogSearchParam);
 
    //获取博客列表
    List<BlogInfo> blogList = blogInfoPageResult.getDataList();
    if (blogList != null && blogList.size()>0)
    {
        for(BlogInfo blog : blogList)
        {
            System.out.println("编号:" + blog.getBlogId() +" 名称:" + blog.getBlogName() + " 积分:" + blog.getBlogPoints() + " " + blog.getBlogUrl()+ " " + blog.getBlogDescribe());
        }
    }
    //分页信息
    System.out.println("当前页码:第" + blogInfoPageResult.getPageIndex()+"页");
    System.out.println("分页大小:每页" + blogInfoPageResult.getPageSize()+"条");
    System.out.println("数据总数:共" + blogInfoPageResult.getTotalData()+"条");
    System.out.println("总页数:共" + blogInfoPageResult.getTotalPage()+"页");
}

 

通过控制器查看执行结果:

(1)解析响应信息结果: 

(2)搜索、分页、排序结果:

3.3 按区间范围搜索

/**
 * 测试:分页搜索列表,按区间范围搜索
 * @author pan_junbiao
 */
@Test
public void searchBlogListPageByRange()
{
    //设置搜索条件
    BlogSearchParam blogSearchParam = new BlogSearchParam();
    blogSearchParam.setBlogDescribe("博客");
    blogSearchParam.setIndexName(_indexName);
    blogSearchParam.setPageIndex(1); //获取第1页数据
    blogSearchParam.setPageSize(5); //每页5条数据
 
    //设置博客积分区间范围
    blogSearchParam.setPointsBegin(100);
    blogSearchParam.setPointsEnd(500);
 
    //执行分页搜索列表
    PageResult<BlogInfo> blogInfoPageResult = blogService.searchBlogListPage(blogSearchParam);
 
    //获取博客列表
    List<BlogInfo> blogList = blogInfoPageResult.getDataList();
    if (blogList != null && blogList.size()>0)
    {
        for(BlogInfo blog : blogList)
        {
            System.out.println("编号:" + blog.getBlogId() +" 名称:" + blog.getBlogName() + " 积分:" + blog.getBlogPoints() + " " + blog.getBlogUrl()+ " " + blog.getBlogDescribe());
        }
    }
    //分页信息
    System.out.println("当前页码:第" + blogInfoPageResult.getPageIndex()+"页");
    System.out.println("分页大小:每页" + blogInfoPageResult.getPageSize()+"条");
    System.out.println("数据总数:共" + blogInfoPageResult.getTotalData()+"条");
    System.out.println("总页数:共" + blogInfoPageResult.getTotalPage()+"页");
}

 

 

通过控制器查看执行结果:

源代码下载:GitHub - kevinpanjunbiao/SpringBootElasticsearch: SpringBoot整合Elasticsearch与综合实例

原文地址:SpringBoot整合Elasticsearch与综合实例(二):搜索、分页、排序_fieldsortbuilder_pan_junbiao的博客-CSDN博客

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值