前言
先送上博客一,可以安装和了解有关elasticsearch的软件elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件。
常见搭建elasticsearch服务有四种方式:
1、TransportClient;2、RestClient;3、Jest; 4、Spring Data Elasticsearch
其中TransportClient和RestClient是Elasticsearch原生的api。TransportClient可以支持2.x,5.x版本,TransportClient将会在Elasticsearch 7.0弃用并在8.0中完成删除,替而代之,我们使用Java High Level REST Client,它使用HTTP请求而不是Java序列化请求。因为公司使用第二种方式使用transport Client 操作elasticsearch服务,所以特意从网上自学习了下 transport Client,特来记录下,最好自己能够搭建一个 elasticsearch 服务,按照上个博客安装好三个软件即可。
本博客项目是比较简单的,主要就是上个博客搭建比较麻烦吧。
博客目录
- elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件、elasticsearch-ik分词器。
- elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
- elasticsearch学习三:elasticsearch-ik分词器的自定义配置 分词内容
- elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
一、新建springboot项目
1. 注意的地方
2. 最终目录结构
二、新增maven依赖
1. ES版本
elasticsearch和kibana的版本都是6.4.2版本
2. 新增依赖
<!--alibaba fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.0.0</version>
</dependency>
3. pom.xml全部依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.feng.springbootelasticsearch</groupId>
<artifactId>springboot-elasticsearch-transport</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-elasticsearch-transport</name>
<description>springboot-elasticsearch-transport</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--alibaba fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
三、业务代码
1. application.properties
这里的内容一定要与 elasticsearch 目录下 /conf/elasticsearch.yml
中的配置一致。
server.port=8087
elasticsearch.cluster-name=elasticsearch
elasticsearch.ip=127.0.0.1
elasticsearch.port=20104
elasticsearch.pool=5
2. ES全局配置类
在config
包下编写ElasticSearchConfig
类,
package com.feng.springbootelasticsearchtransport.config;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
@Slf4j
@Configuration
public class ElasticSearchConfig {
@Value("${elasticsearch.ip}")
private String hostName;
/**
* 端口
*/
@Value("${elasticsearch.port}")
private String port;
/**
* 集群名称
*/
@Value("${elasticsearch.cluster-name}")
private String clusterName;
/**
* 连接池
*/
@Value("${elasticsearch.pool}")
private String poolSize;
/**
* Bean name default 函数名字
* @return
*/
@Bean(name = "transportClient")
public TransportClient transportClient() {
log.info("Elasticsearch初始化开始。。。。。");
TransportClient transportClient = null;
try {
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name", clusterName) //集群名字
.put("client.transport.sniff", true)//增加嗅探机制,找到ES集群
.put("thread_pool.search.size", Integer.parseInt(poolSize))//增加线程池个数,暂时设为5
.build();
//配置信息Settings自定义
transportClient = new PreBuiltTransportClient(esSetting);
TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
transportClient.addTransportAddresses(transportAddress);
log.info("Elasticsearch初始化成功。。。。。");
} catch (Exception e) {
log.error("elasticsearch TransportClient create error!!", e);
}
return transportClient;
}
}
3. 编写elasticsearch工具类
在utils
包下编写ElasticSearchUtil
类,
package com.feng.springbootelasticsearchtransport.utils;
import com.alibaba.fastjson.JSONObject;
import com.feng.springbootelasticsearchtransport.bean.EsPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Component
@Slf4j
public class ElasticSearchUtil {
@Autowired
private TransportClient transportClient;
private static TransportClient client;
/**
* @PostContruct是spring框架的注解
* spring容器初始化的时候执行该方法
*/
@PostConstruct
public void init() {
client = this.transportClient;
}
/**
* 创建索引
*
* @param index
* @return
*/
public static boolean createIndex(String index) {
if(!isIndexExist(index)){
log.info("Index is not exits!");
}else {
log.info("Index is exits!");
}
CreateIndexResponse indexResponse = client.admin().indices().prepareCreate(index).execute().actionGet();
log.info("执行建立成功?" + indexResponse.isAcknowledged());
return indexResponse.isAcknowledged();
}
/**
* 删除索引
*
* @param index
* @return
*/
public static boolean deleteIndex(String index) {
if(!isIndexExist(index)) {
log.info("Index is not exits!");
}
// AcknowledgedResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
DeleteIndexResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
if (dResponse.isAcknowledged()) {
log.info("delete index " + index + " successfully!");
} else {
log.info("Fail to delete index " + index);
}
return dResponse.isAcknowledged();
}
/**
* 判断索引是否存在
*
* @param index
* @return
*/
public static boolean isIndexExist(String index) {
IndicesExistsResponse inExistsResponse = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
if (inExistsResponse.isExists()) {
log.info("Index [" + index + "] is exist!");
} else {
log.info("Index [" + index + "] is not exist!");
}
return inExistsResponse.isExists();
}
/**
* 数据添加,正定ID
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type, String id) {
IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();
log.info("addData response status:{},id:{}", response.status().getStatus(), response.getId());
return response.getId();
}
/**
* 数据添加
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @return
*/
public static String addData(JSONObject jsonObject, String index, String type) {
return addData(jsonObject, index, type, UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
}
/**
* 通过ID删除数据
*
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
*/
public static void deleteDataById(String index, String type, String id) {
DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
log.info("deleteDataById response status:{},id:{}", response.status().getStatus(), response.getId());
}
/**
* 通过ID 更新数据
*
* @param jsonObject 要增加的数据
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @return
*/
public static void updateDataById(JSONObject jsonObject, String index, String type, String id) {
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index).type(type).id(id).doc(jsonObject);
client.update(updateRequest);
}
/**
* 通过ID获取数据
*
* @param index 索引,类似数据库
* @param type 类型,类似表
* @param id 数据ID
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @return
*/
public static Map<String,Object> searchDataById(String index, String type, String id, String fields) {
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
if (StringUtils.isNotEmpty(fields)) {
getRequestBuilder.setFetchSource(fields.split(","), null);
}
GetResponse getResponse = getRequestBuilder.execute().actionGet();
return getResponse.getSource();
}
/**
* 使用分词查询,并分页
*
* @param index 索引名称
* @param type 类型名称,可传入多个type逗号分隔
* @param startPage 当前页
* @param pageSize 每页显示条数
* @param query 查询条件
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField 排序字段
* @param highlightField 高亮字段
* @return
*/
public static EsPage searchDataPage(String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
// 需要显示的字段,逗号分隔(缺省为全部字段)
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
//排序字段
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.DESC);
}
// 高亮(xxx=111,aaa=222)
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
//highlightBuilder.preTags("<span style='color:red' >");//设置前缀
//highlightBuilder.postTags("</span>");//设置后缀
// 设置高亮字段
highlightBuilder.field(highlightField);
searchRequestBuilder.highlighter(highlightBuilder);
}
//searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
searchRequestBuilder.setQuery(query);
// 分页应用
searchRequestBuilder.setFrom(startPage).setSize(pageSize);
// 设置是否按查询匹配度排序
searchRequestBuilder.setExplain(true);
//打印的内容 可以在 Elasticsearch head 和 Kibana 上执行查询
log.info("\n{}", searchRequestBuilder);
// 执行搜索,返回搜索响应信息
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().getTotalHits();
long length = searchResponse.getHits().getHits().length;
log.debug("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField);
return new EsPage(startPage, pageSize, (int) totalHits, sourceList);
}
return null;
}
/**
* 使用分词查询
*
* @param index 索引名称
* @param type 类型名称,可传入多个type逗号分隔
* @param query 查询条件
* @param size 文档大小限制
* @param fields 需要显示的字段,逗号分隔(缺省为全部字段)
* @param sortField 排序字段
* @param highlightField 高亮字段
* @return
*/
public static List<Map<String, Object>> searchListData(String index, String type, QueryBuilder query, Integer size, String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 设置高亮字段
highlightBuilder.field(highlightField);
searchRequestBuilder.highlighter(highlightBuilder);
}
searchRequestBuilder.setQuery(query);
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
searchRequestBuilder.setFetchSource(true);
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.DESC);
}
if (size != null && size > 0) {
searchRequestBuilder.setSize(size);
}
// 打印的内容 可以在 Elasticsearch head 和 Kibana 上执行查询
log.info("\n{}", searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long totalHits = searchResponse.getHits().getTotalHits();
long length = searchResponse.getHits().getHits().length;
log.info("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
if (searchResponse.status().getStatus() == 200) {
// 解析对象
return setSearchResponse(searchResponse, highlightField);
}
return null;
}
/**
* 高亮结果集 特殊处理
*
* @param searchResponse
* @param highlightField
*/
private static List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField) {
List<Map<String, Object>> sourceList = new ArrayList<Map<String, Object>>();
StringBuffer stringBuffer = new StringBuffer();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
searchHit.getSourceAsMap().put("id", searchHit.getId());
if (StringUtils.isNotEmpty(highlightField)) {
System.out.println("遍历 高亮结果集,覆盖 正常结果集" + searchHit.getSourceAsMap());
Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments();
if (text != null) {
for (Text str : text) {
stringBuffer.append(str.string());
}
//遍历 高亮结果集,覆盖 正常结果集
searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString());
}
}
sourceList.add(searchHit.getSourceAsMap());
}
return sourceList;
}
}
4. 编写分页实体类
在bean
包下编写EsPage
类,
package com.feng.springbootelasticsearchtransport.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EsPage {
/**
* 当前页
*/
private int currentPage;
/**
* 每页显示多少条
*/
private int pageSize;
/**
* 总记录数
*/
private int recordCount;
/**
* 本页的数据列表
*/
private List<Map<String, Object>> recordList;
/**
* 总页数
*/
private int pageCount;
/**
* 页码列表的开始索引(包含)
*/
private int beginPageIndex;
/**
* 页码列表的结束索引(包含)
*/
private int endPageIndex;
/**
* 只接受前4个必要的属性,会自动的计算出其他3个属性的值
*
* @param currentPage
* @param pageSize
* @param recordCount
* @param recordList
*/
public EsPage(int currentPage, int pageSize, int recordCount, List<Map<String, Object>> recordList) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.recordCount = recordCount;
this.recordList = recordList;
// 计算总页码
pageCount = (recordCount + pageSize - 1) / pageSize;
// 计算 beginPageIndex 和 endPageIndex
// >> 总页数不多于10页,则全部显示
if (pageCount <= 10) {
beginPageIndex = 1;
endPageIndex = pageCount;
}
// >> 总页数多于10页,则显示当前页附近的共10个页码
else {
// 当前页附近的共10个页码(前4个 + 当前页 + 后5个)
beginPageIndex = currentPage - 4;
endPageIndex = currentPage + 5;
// 当前面的页码不足4个时,则显示前10个页码
if (beginPageIndex < 1) {
beginPageIndex = 1;
endPageIndex = 10;
}
// 当后面的页码不足5个时,则显示后10个页码
if (endPageIndex > pageCount) {
endPageIndex = pageCount;
beginPageIndex = pageCount - 10 + 1;
}
}
}
}
5. 测试类
在测试模块中进行编写测试类,进行CRUD操作。
package com.feng.springbootelasticsearchtransport;
import com.alibaba.fastjson.JSONObject;
import com.feng.springbootelasticsearchtransport.bean.EsPage;
import com.feng.springbootelasticsearchtransport.utils.ElasticSearchUtil;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
@SpringBootTest
class SpringbootElasticsearchTransportApplicationTests {
/**
* 测试索引
*/
private String indexName="test_index";
/**
* 类型
*/
private String esType="external";
@Test
void contextLoads() {
System.out.println("111");
}
/**
* 创建索引
*/
@Test
void test01CreateIndex(){
if(!ElasticSearchUtil.isIndexExist(indexName)) {
ElasticSearchUtil.createIndex(indexName);
} else{
System.out.println("索引已经存在");;
}
System.out.println("索引创建成功");
}
/**
* 插入记录
*/
@Test
void test02InsertJson(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", DateUtils.formatDate(new Date()));
jsonObject.put("age", 25);
jsonObject.put("name", "j-" + new Random(100).nextInt());
jsonObject.put("date", new Date());
String id = ElasticSearchUtil.addData(jsonObject, indexName, esType, jsonObject.getString("id"));
System.out.println("id:"+id);
}
/**
* 删除
*/
@Test
void test03Delete(){
String id = "Wed, 16 Dec 2020 07:19:19 GMT";
if(StringUtils.isNotBlank(id)) {
ElasticSearchUtil.deleteDataById(indexName, esType, id);
System.out.println("删除id=" + id);;
} else{
System.out.println("id为空");;
}
}
/**
* 更新
*/
@Test
void test04Update(){
String id = "Wed, 16 Dec 2020 07:19:19 GMT";
if(StringUtils.isNotBlank(id)) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", id);
jsonObject.put("age", 31);
jsonObject.put("name", "修改");
jsonObject.put("date", new Date());
ElasticSearchUtil.updateDataById(jsonObject, indexName, esType, id);
System.out.println("id=" + id);;
}
else{
System.out.println("id为空");;
}
}
/**
* 获取数据
*/
@Test
void test05GetData(){
String id = "Wed, 16 Dec 2020 07:19:19 GMT";
if(StringUtils.isNotBlank(id)) {
Map<String, Object> map= ElasticSearchUtil.searchDataById(indexName,esType,id,null);
System.out.println(JSONObject.toJSONString(map));;
}
else{
System.out.println("id为空");;
}
}
/**
*
*/
@Test
void test06QueryMatchData(){
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolean matchPhrase = false;
if (matchPhrase == Boolean.TRUE) {
boolQuery.must(QueryBuilders.matchPhraseQuery("name", "修"));
} else {
boolQuery.must(QueryBuilders.matchQuery("name", "修"));
}
List<Map<String, Object>> list = ElasticSearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
System.out.println(JSONObject.toJSONString(list));;
}
/**
* 通配符查询数据
* 通配符查询 ? 用来匹配1个任意字符,* 用来匹配零个或者多个字符
* 0 条数据
*/
@Test
void test07QueryWildcardData(){
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name.keyword", "j-*466");
List<Map<String, Object>> list = ElasticSearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
System.out.println(JSONObject.toJSONString(list));;
}
/**
* 正则查询
* 0 条数据
*/
@Test
void test08QueryRegexpData(){
QueryBuilder queryBuilder = QueryBuilders.regexpQuery("name.keyword", "j--[0-9]{1,11}");
List<Map<String, Object>> list = ElasticSearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
System.out.println(JSONObject.toJSONString(list));;
}
/**
* 查询数字范围数据
*/
@Test
void test09QueryIntRangeData(){
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("age").from(21).to(100));
List<Map<String, Object>> list = ElasticSearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
System.out.println(JSONObject.toJSONString(list));;
}
/**
* 查询日期范围数据
*/
@Test
void test10QueryDateRangeData(){
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z").to("2021-04-25T10:03:08.081Z"));
List<Map<String, Object>> list = ElasticSearchUtil.searchListData(indexName, esType, boolQuery, 10, null, null, null);
System.out.println(JSONObject.toJSONString(list));;
}
/**
* 查询分页
* startPage 第几条记录开始 测试 1
* pageSize 每页大小 测试 10
* @return
*/
@Test
void test11QueryPage(){
int startPage = 1;
int pageSize = 10;
if(StringUtils.isNotBlank(String.valueOf(startPage))&& StringUtils.isNotBlank(String.valueOf(pageSize))) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.rangeQuery("date").from("2018-04-25T08:33:44.840Z")
.to("2021-04-25T10:03:08.081Z"));
EsPage list = ElasticSearchUtil.searchDataPage(indexName, esType, Integer.parseInt(startPage+""), Integer.parseInt(pageSize+""), boolQuery, null, null, null);
System.out.println(JSONObject.toJSONString(list));
}
else{
System.out.println("startPage或者pageSize缺失");
}
}
}
6. 测试结果
第五步中的测试类中的所有方法都已测试,均已测试成功。