玩转 Spring boot 系列:(一)使用 Idea 搭建 Spring boot Maven 多模块父子工程(图解)
玩转 Spring boot 系列:(二)配置多开发环境,集成druid数据源(图解)
玩转 Spring boot 系列:(三)集成mybatis,实现增删改查(图解)
玩转 Spring boot 系列:(四)mybatis 集成分页插件 pagehelper 并自定义分页结果集
玩转 Spring boot 系列:(五)集成 redis 客户端 Jedis
玩转 Spring boot 系列:(六)优雅的全局异常处理 和通用响应器
玩转 Spring boot 系列:(七)集成七牛实现文件上传
玩转 Spring boot 系列:(八)基于redis的用户登录注册以及过滤器的实现
spring boot 基于阿里云商业版的RocketMQ消息实战后,接下来我们将集成Elasticsearch 最新版本7.8到项目中,进行搜索实战
代码地址:Spring boot 集成基于Elasticsearch 7.8 搜索实战
1、搭建es 的教程,受限于篇幅这里就不展开了,如果感兴趣的朋友很多,回来再单独出一篇文章。
打建好es之后,在浏览器中输入:
http://127.0.0.1:9200/_cat/health
出现green 则意味着,es搭建成功!可以与spring boot 进行集成。
2、由于使用的是新版本 7.8,所以spring boot 的pom.xml文件配置如下:
org.elasticsearch
elasticsearch
${elasticsearch.version}
org.elasticsearch.client
elasticsearch-rest-client
${elasticsearch.version}
org.elasticsearch.client
elasticsearch-rest-high-level-client
${elasticsearch.version}
org.elasticsearch
elasticsearch
org.elasticsearch.client
elasticsearch-rest-client
3、配置application.yml文件
如果es的生产和开发都是一个库,那么我们可以将 连接信息配置到 application.yml文件,如果有多套不同的配置,建议配置到 application-dev.yml文件中。
liren:
es:
open: true
host: 127.0.0.1
port: 9200
scheme: http
connTimeout: 3000
socketTimeout: 5000
connectionRequestTimeout: 500
4、新建 es 配置类 ElasticConfig.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liren.basic.common.exception.RRException;
import lombok.Data;
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.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
/**
* @description: ElasticConfig
* @author: LiRen
**/
@Data
@Component
@ConfigurationProperties(prefix = "liren.es")
public class ElasticConfig {
private boolean open;
private String host;
private int port;
private String scheme;
private int connTimeout;
private int socketTimeout;
private int connectionRequestTimeout;
@Bean
public RestClientBuilder restClientBuilder() {
return RestClient.builder(makeHttpHost());
}
@Bean
public RestClient elasticsearchRestClient() {
return RestClient.builder(new HttpHost(host, port, scheme))
.setRequestConfigCallback(restClientBuilder -> restClientBuilder
.setConnectTimeout(connTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout))
.build();
}
private HttpHost makeHttpHost() {
return new HttpHost(host, port, scheme);
}
@Bean
public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder) {
return new RestHighLevelClient(restClientBuilder);
}
/**
* 读取 resource目录下的文件内容
* @param path
* @param key
* @return
* @throws IOException
*/
public String JsonTest(String path, String key) throws IOException {
InputStream stream = this.getClass().getResourceAsStream(path);
if (stream == null) {
throw new RRException("读取文件失败");
} else {
JSONObject json = JSON.parseObject(stream, JSONObject.class);
String val = json.getString(key);
return val;
}
}
}
5、新建es的内容实体 EsEntity.java
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.util.UUID;
/**
* @description: ElasticEntity es 文档实体
* @author: LiRen
**/
@Data
public class EsEntity {
/**
* 主键标识,用户ES持久化,必须 显式的指定 id。
*/
private String id;
/**
* JSON对象,实际存储数据
*/
private T data;
public EsEntity(String id, T data) {
this.id = (StringUtils.isBlank(id) ? UUID.randomUUID().toString() : id);
this.data = data;
}
}
6、新建es工具类 EsUtil.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.liren.basic.common.page.Page;
import com.liren.basic.common.response.JsonReturn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.client.RequestOptions.DEFAULT;
/**
* @description: elasticsearchUtil elasticsearch 操作类
* @author: LiRen
**/
@Slf4j
@Component
public class EsUtil {
private static RestHighLevelClient restHighLevelClient;
public EsUtil(RestHighLevelClient restHighLevelClient) {
EsUtil.restHighLevelClient = restHighLevelClient;
}
/**
* @param idxName 索引名称
* @param idxSql 索引描述
* @Description: 创建索引
* @return: {@link boolean}
* @author: LiRen
*/
public static boolean createIndex(String idxName, String idxSql) {
try {
if (!indexExist(idxName)) {
log.info(" idxName= {} 已经存在,idxSql= {}", idxName, idxSql);
return false;
}
CreateIndexRequest request = new CreateIndexRequest(idxName);
buildSetting(request);
request.mapping(idxSql, XContentType.JSON);
// request.settings() 手工指定Setting
CreateIndexResponse res = restHighLevelClient.indices().create(request, DEFAULT);
if (!res.isAcknowledged()) {
throw new RuntimeException("初始化失败");
}
log.info("createIndex is SUCCESS!!,idxName= {}, ,idxSql= {}", idxName, idxSql);
return res.isAcknowledged();
} catch (Exception e) {
e.printStackTrace();
log.error("createIndex is FAIL!!,idxName= {}, ,idxSql= {}", idxName, idxSql);
throw new RuntimeException(e);
}
}
/**
* @param idxName index名
* @return boolean
* @Description: 断某个index是否存在
* @author: LiRen
*/
public static boolean indexExist(String idxName) throws Exception {
GetIndexRequest request = new GetIndexRequest(idxName);
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
return restHighLevelClient.indices().exists(request, DEFAULT);
}
/**
* @param idxName index名
* @return boolean
* @Description: 断某个index是否存在
* @author: LiRen
*/
public static boolean isExistsIndex(String idxName) throws Exception {
return restHighLevelClient.indices().exists(new GetIndexRequest(idxName), DEFAULT);
}
/**
* @param request
* @Description: 设置分片
* @author: LiRen
*/
public static void buildSetting(CreateIndexRequest request) {
request.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2));
}
/**
* @param idxName index
* @param entity 对象
* @return
* @Description: 新增 / 更新 数据
* @author: LiRen
*/
public static RestStatus insertOrUpdateOne(String idxName, EsEntity entity) {
IndexRequest request = new IndexRequest(idxName)
.id(entity.getId())
.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
try {
RestStatus status = restHighLevelClient.index(request, DEFAULT).status();
log.info("insertOrUpdateOne -- idxName={}, EsEntity={}, RestStatus={}", idxName, JSON.toJSONString(entity), "OK");
return status;
// return indexResponse.status().equals(RestStatus.CREATED);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param idxName 表名称
* @param data 插入列表
* @return
* @Description: 批量插入数据
* @author: LiRen
*/
public static RestStatus insertBatch(String idxName, List data) {
BulkRequest request = new BulkRequest();
data.forEach(item -> request.add(new IndexRequest(idxName).id(item.getId())
.source(JSON.toJSONString(item.getData()), XContentType.JSON)));
try {
return restHighLevelClient.bulk(request, DEFAULT).status();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param idxName
* @return
* @Description: 删除索引
* @author: LiRen
*/
public static boolean deleteIndex(String idxName) {
try {
if (!indexExist(idxName)) {
log.error(" idxName={} 已经存在", idxName);
return false;
}
AcknowledgedResponse result = restHighLevelClient.indices().delete(new DeleteIndexRequest(idxName), DEFAULT);
log.info("deleteIndex -- idxName={}, result={}", idxName, JSON.toJSONString(result.isAcknowledged()));
return result.isAcknowledged();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param idxName
* @param id
* @Description: 根据 id 删除
* @return: {@link RestStatus}
* @author: LiRen
*/
public static RestStatus deleteById(String idxName, String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(idxName, id);
RestStatus status = restHighLevelClient.delete(deleteRequest, DEFAULT).status();
log.info("deleteById -- idxName={}, id= {}, status={}", idxName, id, "OK");
return status;
}
/**
* @param idxName
* @param fieldKey
* @param fieldVal
* @Description: 根据条件 删除文档
* @return: {@link long}
* @author: LiRen
*/
public static long deleteByQuery(String idxName, String fieldKey, String fieldVal) {
DeleteByQueryRequest request = new DeleteByQueryRequest(idxName);
request.setQuery(new TermQueryBuilder(fieldKey, fieldVal));
request.setBatchSize(10000);
request.setConflicts("proceed");
try {
long total = restHighLevelClient.deleteByQuery(request, DEFAULT).getTotal();
// fieldName key
log.info("deleteByQuery -- idxName={}, fieldKey= {}, fieldVal= {}, status= {}", idxName, fieldKey, fieldVal, total);
return total;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param idxName index
* @param idList 待删除列表
* @return
* @Description: 批量删除
* @author: LiRen
*/
public static RestStatus deleteBatch(String idxName, Collection> idList) {
BulkRequest request = new BulkRequest();
idList.forEach(item -> request.add(new DeleteRequest(idxName, item.toString())));
try {
return restHighLevelClient.bulk(request, DEFAULT).status();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// ------------------------->>>>>>>>>>>>>>>>>>>>>>>>>> 查找
/**
* @param idxName
* @param id
* @param clazz
* @Description: 根据 id 进行查找
* @return: {@link T}
* @author: LiRen
*/
public static T getDocById(String idxName, String id, Class clazz) throws IOException {
GetResponse response = getResponse(idxName, id);
if (response.isExists()) {
log.info("getDocById -- idxName={}, id= {}, status={}", idxName, id, "OK");
return JSONObject.parseObject(response.getSourceAsString(), clazz);
} else {
log.error("没有找到该 id 的文档");
}
return null;
}
/**
* @Description: 根据 id 进行查找
* @return: {@link Object}
* @author: LiRen
*/
public static Object getDocById(String idxName, String id) throws IOException {
GetResponse response = getResponse(idxName, id);
if (response.isExists()) {
log.info("getDocById -- idxName={}, id= {}, status={}", idxName, id, "OK");
return JSONObject.parseObject(response.getSourceAsString());
} else {
log.error("没有找到该 id 的文档");
}
return null;
}
private static GetResponse getResponse(String idxName, String id) throws IOException {
GetRequest getRequest = new GetRequest(idxName, id);
return restHighLevelClient.get(getRequest, DEFAULT);
}
/**
* @param idxName
* @param aggregation
* @Description: 条件聚合
* @return: {@link Aggregations}
* @author: LiRen
*/
public static Aggregations aggregationsSearchUser(String idxName, TermsAggregationBuilder aggregation) throws IOException {
SearchRequest request = new SearchRequest(idxName);
SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
request.source(builder);
SearchResponse searchResponse = restHighLevelClient.search(request, DEFAULT);
return searchResponse.getAggregations();
}
// -------------------------------------------------------------------------
/**
* 前方高能预警,非战斗人员 请迅速撤离!!!
* 开始构建 DSL 搜索。
*/
/**
* @param builder
* @param real true 分词;false 不分词;默认为 true
* @param fieldKey
* @param fieldVal
* @Description: 追加查询条件,构造查询引擎
* @author: LiRen
*/
public static void builderQuery(SearchSourceBuilder builder, boolean real, String fieldKey, String fieldVal) {
if (StringUtils.isBlank(fieldKey) || StringUtils.isBlank(fieldVal)) {
builderQuery(builder);
return;
}
if (real) {
// 会分词处理
builder.query(QueryBuilders.matchQuery(fieldKey, fieldVal));
} else {
builder.query(QueryBuilders.termsQuery(fieldKey, fieldVal));
}
}
public static void builderQuery(SearchSourceBuilder builder, String fieldKey, String fieldVal) {
builderQuery(builder, true, fieldKey, fieldVal);
}
public static void builderQuery(SearchSourceBuilder builder) {
builder.query(QueryBuilders.matchAllQuery());
}
/**
* @param builder
* @param includes 包含的字段 AA,BB,CC
* @param excludes 不包含的字段
* @Description: 字段过滤器
* eg: AA,BB,CC,DD,EE,FF -> 结果:AA,BB,CC
* @return: {@link SearchSourceBuilder}
* @author: LiRen
*/
public static SearchSourceBuilder builderfetch(SearchSourceBuilder builder, @Nullable String[] includes, @Nullable String[] excludes) {
builder.fetchSource(includes, excludes);
return builder;
}
/**
* @param builder
* @param orderKey 排序字段
* @param orderRule 排序方式,仅限:ASC,DESC(不区分大小写)
* @Description: 设置排序
* @return: {@link SearchSourceBuilder}
* @author: LiRen
*/
public static SearchSourceBuilder builderSort(SearchSourceBuilder builder, String orderKey, String orderRule) {
builder.sort(orderKey, SortOrder.fromString(orderRule));
return builder;
}
/**
* @param builder
* @param lineTag 高亮标签: 、
* @param fieldKey 高亮的字段
* @Description: 设置高亮
* @return: {@link SearchSourceBuilder}
* @author: LiRen
*/
public static SearchSourceBuilder builderHighlight(SearchSourceBuilder builder, String lineTag, String fieldKey) {
HighlightBuilder highlight = new HighlightBuilder();
highlight.preTags("<" + lineTag + ">");
highlight.postTags("" + lineTag + ">");
highlight.fields().add(new HighlightBuilder.Field(fieldKey));
builder.highlighter(highlight);
return builder;
}
/**
* @Description: 构建游标
* @return: {@link Scroll}
* @author: LiRen
*/
public static Scroll builderScroll() {
return new Scroll(TimeValue.timeValueMinutes(1L));
}
/**
* @param builder
* @param page
* @Description: 设置分页参数规则
* @author: LiRen
*/
public static void builderPage(SearchSourceBuilder builder, Page page) {
int from = (page.getPage() - 1) * page.getRows();
builder.from(from);
builder.size(page.getRows());
}
/**
* @Description: 构建搜索请求,设置数据源
* 发起查询
* @return: {@link SearchResponse}
* @author: LiRen
*/
public static SearchResponse builderSearch(String idxName, SearchSourceBuilder builder) throws IOException {
SearchRequest request = new SearchRequest(idxName);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
request.source(builder);
return restHighLevelClient.search(request, DEFAULT);
}
public static SearchResponse builderSearch(String idxName, SearchSourceBuilder builder, Scroll scroll) throws IOException {
SearchRequest request = new SearchRequest(idxName);
builder.size(10000);
request.scroll(scroll);
request.source(builder);
return restHighLevelClient.search(request, DEFAULT);
}
/**
* @param response
* @param page 是否分页
* @param clazz 序列化实体
* @Description: 获取查询结果
* @return: {@link Map}
* @author: LiRen
*/
public static Map getSearchResult(SearchResponse response, Page page, Class clazz) {
SearchHits searchHits = response.getHits();
// 分页请求的总数是否一致
page.setRecords(searchHits.getTotalHits().value);
page.setTotal(Math.toIntExact((page.getRecords() + page.getRows() - 1) / page.getRows()));
List list = HitList(searchHits, clazz);
return page.esInfo(JsonReturn.CODE_SUCCESS, list);
}
public static Map getSearchResult(SearchResponse response, Page page) {
return getSearchResult(response, page, null);
}
public static List getSearchResult(SearchResponse response, Class clazz) {
return HitList(response.getHits(), clazz);
}
public static List getSearchResult(SearchResponse response) {
return HitList(response.getHits(), null);
}
public static List getSearchResult(SearchResponse response, Scroll scroll, Class clazz) {
String scrollId = response.getScrollId();
List list = getSearchResult(response, clazz);
SearchHit[] searchHits = response.getHits().getHits();
while (searchHits != null && searchHits.length > 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
try {
response = restHighLevelClient.scroll(scrollRequest, DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
scrollId = response.getScrollId();
searchHits = response.getHits().getHits();
list.addAll(getSearchResult(response, clazz));
}
ClearScrollRequest clear = new ClearScrollRequest();
clear.addScrollId(scrollId);
try {
restHighLevelClient.clearScroll(clear, DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* @param searchHits
* @param clazz
* @Description: 处理返回结果集
* @return: {@link List}
* @author: LiRen
*/
public static List HitList(SearchHits searchHits, Class clazz) {
SearchHit[] hits = searchHits.getHits();
List list = new ArrayList<>(hits.length);
if (clazz == null) {
for (SearchHit hit : hits) {
list.add(hit.getSourceAsString());
}
} else {
Gson gson = new Gson();
for (SearchHit hit : hits) {
list.add(gson.fromJson(hit.getSourceAsString(), clazz));
}
}
return list;
}
}
7、新建es 抽象代码 EsService.java
import com.liren.basic.common.page.Page;
import com.liren.basic.common.response.JsonReturn;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @description: esUtilService ES 调用方法
* 别问为啥是 Service,问就是 懒!
* @author: LiRen
**/
@Component
public class EsService {
// ------------------------->>>>>>>>>>>>>>>>>>>>>>>>>> 新增
/**
* @param idxName 索引名称
* @param idxSql 索引描述
* @return
* @Description: 创建索引
* @author: LiRen
*/
public boolean createIndex(String idxName, String idxSql) {
return EsUtil.createIndex(idxName, idxSql);
}
/**
* @param idxName index
* @param entity 对象
* @return
* @Description: 新增 数据
* @author: LiRen
*/
public RestStatus insertOne(String idxName, EsEntity entity) {
return EsUtil.insertOrUpdateOne(idxName, entity);
}
/**
* @param idxName index
* @param data 插入列表
* @return
* @Description: 批量插入数据
* @author: LiRen
*/
public RestStatus insertBatch(String idxName, List data) {
return EsUtil.insertBatch(idxName, data);
}
// ------------------------->>>>>>>>>>>>>>>>>>>>>>>>>> 删除
/**
* @param idxName
* @return
* @Description: 删除索引
* @author: LiRen
*/
public boolean deleteIndex(String idxName) {
return EsUtil.deleteIndex(idxName);
}
/**
* @param idxName
* @param id
* @Description: 根据 id 删除
* @return: {@link RestStatus}
* @author: LiRen
*/
public RestStatus deleteById(String idxName, String id) throws IOException {
return EsUtil.deleteById(idxName, id);
}
/**
* @param idxName
* @param fieldKey 匹配在给定字段中含有该词条的文档
* @param fieldVal
* @Description: 根据文档内容的 key 进行删除
* @return: {@link BulkByScrollResponse}
* @author: LiRen
*/
public long deleteByKey(String idxName, String fieldKey, String fieldVal) {
return EsUtil.deleteByQuery(idxName, fieldKey, fieldVal);
}
/**
* @param idxName index
* @param data 待删除列表
* @return
* @Description: 批量删除
* @author: LiRen
*/
public RestStatus deleteBatch(String idxName, List data) {
return EsUtil.deleteBatch(idxName, data);
}
// ------------------------->>>>>>>>>>>>>>>>>>>>>>>>>> 更新
/**
* @param idxName index
* @param entity 对象
* @return
* @Description: 更新 数据
* @author: LiRen
*/
public RestStatus UpdateById(String idxName, EsEntity> entity) {
return EsUtil.insertOrUpdateOne(idxName, entity);
}
// ------------------------->>>>>>>>>>>>>>>>>>>>>>>>>> 查找
/**
* @param idxName
* @param id
* @param clazz
* @Description: 根据 id 进行查找
* @return: {@link T}
* @author: LiRen
*/
public T getDocById(String idxName, String id, Class clazz) throws IOException {
return EsUtil.getDocById(idxName, id, clazz);
}
/**
* @param idxName
* @param id
* @Description: 根据 id 进行查找
* @return: {@link Object}
* @author: LiRen
*/
public Object getDocById(String idxName, String id) throws IOException {
return EsUtil.getDocById(idxName, id);
}
/**
* @param idxName index
* @param fieldKey 检索元素的key
* @param fieldVal 检索元素的值
* @param clazz 结果类对象
* @Description: 条件检索
* @return: {@link List}
* @author: LiRen
*/
public List getDocsByKey(String idxName, boolean real, String fieldKey, String fieldVal, Class clazz) throws IOException {
return search(idxName, real, fieldKey, fieldVal, clazz);
}
public Map getDocsByKey(String idxName, String fieldKey, String fieldVal, Page page, Class clazz) throws IOException {
return search(idxName, fieldKey, fieldVal, page, clazz);
}
public Map getDocsByKey(String idxName, boolean real, String fieldKey, String fieldVal, Page page, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
if (page.getRows() * page.getPage() >= 10000) {
return page.esInfo(JsonReturn.CODE_ERROR);
}
EsUtil.builderPage(builder, page);
EsUtil.builderQuery(builder, real, fieldKey, fieldVal);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder), page, clazz);
}
/**
* @param idxName index
* @param fieldKey 检索元素的key
* @param fieldVal 检索元素的值
* @Description: 条件检索
* @return: {@link List}
* @author: LiRen
*/
public List getDocsByKey(String idxName, String fieldKey, String fieldVal) throws IOException {
return search(idxName, fieldKey, fieldVal);
}
/**
* @param idxName index
* @param clazz 结果类对象
* @Description: 获取 全部 列表
* 默认只显示 10条
* @return: {@link List}
* @author: LiRen
*/
public List getDocList(String idxName, Class clazz) throws IOException {
return search(idxName, clazz);
}
/**
* @param idxName index
* @Description: 获取 全部 列表
* @return: {@link List}
* @author: LiRen
*/
public List getDocList(String idxName) throws IOException {
return search(idxName);
}
/**
* @param idxName
* @param fieldKey
* @param fieldVal
* @param clazz
* @Description: 查询全部
* @return: {@link List}
* @author: LiRen
*/
public List getDocALL(String idxName, String fieldKey, String fieldVal, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
EsUtil.builderQuery(builder, fieldKey, fieldVal);
// 构建全量查询
final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
SearchResponse response = EsUtil.builderSearch(idxName, builder, scroll);
return EsUtil.getSearchResult(response, scroll, clazz);
}
public List getDocALL(String idxName, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
EsUtil.builderQuery(builder);
// 构建全量查询
Scroll scroll = EsUtil.builderScroll();
SearchResponse response = EsUtil.builderSearch(idxName, builder, scroll);
return EsUtil.getSearchResult(response, scroll, clazz);
}
/**
* @param idxName
* @param aggregation
* @Description: 条件聚合
* @return: {@link Aggregations}
* @author: LiRen
*/
public Aggregations aggregationsSearchUser(String idxName, TermsAggregationBuilder aggregation) throws IOException {
return EsUtil.aggregationsSearchUser(idxName, aggregation);
}
// -----------------------------------------------------------
/**
* @param idxName index
* @param fieldKey 检索元素的key
* @param fieldVal 检索元素的值
* @param clazz 结果类对象
* @Description: 检索
* @return: {@link List}
* @author: LiRen
*/
public List search(String idxName, String fieldKey, String fieldVal, Class clazz) throws IOException {
return search(idxName, false, fieldKey, fieldVal, clazz);
}
public List search(String idxName, boolean real, String fieldKey, String fieldVal, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
EsUtil.builderQuery(builder, real, fieldKey, fieldVal);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder), clazz);
}
public List search(String idxName, String fieldKey, String fieldVal) throws IOException {
return search(idxName, fieldKey, fieldVal, null);
}
public List search(String idxName, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
EsUtil.builderQuery(builder);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder), clazz);
}
public List search(String idxName) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
EsUtil.builderQuery(builder);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder));
}
/**
* @Description: 构建分页搜索请求
* @return: {@link Page}
* @author: LiRen
*/
public Map search(String idxName, String fieldKey, String fieldVal, Page page, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
if (page.getRows() * page.getPage() >= 10000) {
return page.esInfo(JsonReturn.CODE_ERROR);
}
EsUtil.builderPage(builder, page);
EsUtil.builderQuery(builder, fieldKey, fieldVal);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder), page, clazz);
}
public Map search(String idxName, Page page) throws IOException {
return search(idxName, page, null);
}
public Map search(String idxName, Page page, Class clazz) throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
if (page.getRows() * page.getPage() >= 10000) {
return page.esInfo(JsonReturn.CODE_ERROR);
}
EsUtil.builderPage(builder, page);
EsUtil.builderQuery(builder);
return EsUtil.getSearchResult(EsUtil.builderSearch(idxName, builder), page, clazz);
}
}
抽取成工具类的原因是因为,可以重用,封装代码,减少冗余。
创作不易,各位的支持和认可,就是我创作的最大动力,
【转载请联系本人】 如有问题,请联系我。欢迎斧正!不胜感激 !
求点赞 求关注❤️ 求分享 求留言