赞
踩
首先搭建一个项目,引入pom依赖,引入es的相关jar包
- <!--引入elasticsearch相关jar包-->
- <dependency>
- <groupId>org.elasticsearch.client</groupId>
- <artifactId>elasticsearch-rest-high-level-client</artifactId>
- <version>6.8.8</version>
- <exclusions>
- <exclusion>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.elasticsearch.client</groupId>
- <artifactId>elasticsearch-rest-client</artifactId>
- <version>6.8.8</version>
- </dependency>
-
- <dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <version>6.8.8</version>
- </dependency>
在application.yml中配置相关属性值,此处使用的es的集群地址是本地多个虚拟机启动的集群模式
- elasticsearch:
- config:
- host: 192.168.236.131:9200,192.168.236.130:9200,192.168.236.129:9200
- requestType: csrcb
- connectTimeout: 1000
- socketTimeout: 5000
- maxRetryTimeout: 5000
- connRequestTimeOut: 1000
定义配置类获取配置文件的属性值
- package com.csrcb.config;
-
- import lombok.Data;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Configuration;
-
- /**
- * @Classname EsClientConfig
- * @Description 获取es的相关配置属性,以及属性值
- * @Date 2021/6/2 17:30
- * @Created by gangye
- */
- @Configuration
- @Data
- public class EsClientConfig {
- @Value("${elasticsearch.config.host}")
- private String hosts;
-
- @Value("${elasticsearch.config.connectTimeout}")
- private int connectTimeout;
-
- @Value("${elasticsearch.config.socketTimeout}")
- private int socketTimeout;
-
- @Value("${elasticsearch.config.maxRetryTimeout}")
- private int maxRetryTimeout;
-
- @Value("${elasticsearch.config.connRequestTimeOut}")
- private int connRequestTimeOut;
-
- }
定义es的客户端连接
- package com.csrcb.config;
-
- import com.csrcb.common.DefineConstant;
- import org.apache.http.HttpHost;
- import org.apache.http.client.config.RequestConfig;
- import org.elasticsearch.client.RestClient;
- import org.elasticsearch.client.RestClientBuilder;
- import org.elasticsearch.client.RestHighLevelClient;
-
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
-
- /**
- * @Classname EsClient
- * @Description es的客户端连接
- * @Date 2021/6/3 9:24
- * @Created by gangye
- */
- public class EsClient {
- public static String hosts;
-
- public static int connectTimeout;
-
- public static int socketTimeout;
-
- public static int maxRetryTimeout;
-
- public static int connRequestTimeOut;
-
- private static RestHighLevelClient restHighLevelClient = null;
-
- public EsClient(){
- EsClientConfig esClientConfig = new EsClientConfig();
- hosts = esClientConfig.getHosts();
- connectTimeout = esClientConfig.getConnectTimeout();
- socketTimeout = esClientConfig.getSocketTimeout();
- maxRetryTimeout = esClientConfig.getMaxRetryTimeout();
- connRequestTimeOut = esClientConfig.getConnRequestTimeOut();
- }
-
- public static RestHighLevelClient getInstance(){
- if (restHighLevelClient == null){
- synchronized (RestHighLevelClient.class){
- restHighLevelClient = createClient();
- }
- }
- return restHighLevelClient;
- }
-
- private static RestHighLevelClient createClient(){
- List<String> sockets = Arrays.asList(hosts.split(DefineConstant.COMMAN_SIGN));
- List<HttpHost> httpHosts = new ArrayList<>();
- for (String socket : sockets){
- httpHosts.add(new HttpHost(socket.split(DefineConstant.COLON_SIGN)[0], Integer.valueOf(socket.split(DefineConstant.COLON_SIGN)[1]),"http"));
- }
- RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[0])).setMaxRetryTimeoutMillis(maxRetryTimeout);
- builder.setRequestConfigCallback((RequestConfig.Builder requestConfigBuilder) -> {
- requestConfigBuilder.setConnectTimeout(connectTimeout);
- requestConfigBuilder.setConnectionRequestTimeout(connRequestTimeOut);
- requestConfigBuilder.setSocketTimeout(socketTimeout);
- return requestConfigBuilder;
- });
-
- restHighLevelClient = new RestHighLevelClient(builder);
- return restHighLevelClient;
- }
- }
定义常量值
- package com.csrcb.common;
-
- /**
- * @Classname DefineConstant
- * @Description 定义一些常量值
- * @Date 2021/6/3 10:00
- * @Created by gangye
- */
- public class DefineConstant {
- /**
- * 逗号分隔符
- */
- public static final String COMMAN_SIGN = ",";
-
- /**
- * 等号分隔符
- */
- public static final String EQUALITY_SIGN = "=";
-
- /**
- * 冒号分隔符
- */
- public static final String COLON_SIGN = ":";
-
- /**
- * es的索引文档类型
- */
- public static final String SEARCH_REQUEST_TYPE = "csrcb";
-
- //区间左闭
- public static final String INTERVAL_CLOSE_LEFT = "[";
- //区间右闭
- public static final String INTERVAL_CLOSE_RIGHT = "]";
- //区间左开
- public static final String INTERVAL_OPEN_LEFT = "(";
- //区间右开
- public static final String INTERVAL_OPEN_RIGHT = ")";
-
- public static final String INTERVAL_OPEN_VALUE = "open";
-
- public static final String INTERVAL_CLOSE_VALUE = "close";
-
- public static final String ZERP_MONEY = "0.00";
- }
查询的工具类,支持多条件等值查询,区间范围查询,模糊查询
- /**
- * @Description ElasticSearch条件查询
- * @param tableName (索引名)也可以类似的说成表名
- * @param equalsCondition 关键字等值条件
- * 若是一个字符串以%结尾,则匹配以去掉%的字符串开头的记录
- * 若是一个字符串以*开头或结尾,则模糊匹配去掉*的记录 类似于sql中的like '%str%'
- * 若传入的是一个普通的字符串,则等值查询
- * 若传入的是一个集合,则使用的是in条件查询
- * @param rangeCondition 条件范围查询
- * 字段,字段对应值的区间,区间格式[,]/(,)/[,)/(,],逗号的左右可以没值
- * @param orderBy 排序字段
- * 若是字段以中划线-开头,则使用降序排序,类似于sql中的desc
- * 若正常字段排序,则使用增序排序,类似于sql中的asc
- * @param pageNum 页数
- * @param pageSize 每页大小
- * @return
- */
- public static Map<String ,Object> queryForEs(String tableName, Map<String, Object> equalsCondition, Map<String, Object> rangeCondition, List<String> orderBy, int pageNum, int pageSize){
- Map<String, Object> resultMap = new HashMap<>(8);
- List<Map<String,Object>> queryResult = new ArrayList<>();
- long totalNum = 0;
- SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
- BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
- // and 等值查询
- // 某一field=具体的值; 也可以某一field 的值 in 具体定义集合里的值
- if (null != equalsCondition && !equalsCondition.isEmpty()){
- for (Map.Entry<String ,Object> entry : equalsCondition.entrySet()){
- String key = entry.getKey();
- //由于我创建索引的时候使用字符串不分词使用的.keyword类型
- if (key.endsWith("_s")){
- queryValueBuild(boolQueryBuilder, key + ".keyword", entry.getValue());
- }else{
- queryValueBuild(boolQueryBuilder, key, entry.getValue());
- }
- }
- }
- //范围查询
- if (null != rangeCondition && !rangeCondition.isEmpty()){
- rangeValueBuild(boolQueryBuilder, rangeCondition);
- }
- sourceBuilder.query(boolQueryBuilder);
- //排序
- if (null != orderBy && !orderBy.isEmpty()){
- buildSort(sourceBuilder, orderBy);
- }
- //分页(es分页查询默认是查询返回10条记录,而深度分页,默认是10000条数据,也就是一次性最多返回10000条,设置size就可以实现,但是如果实际数据量特别大,可以使用scroll游标查询,此处主要常规分页查询)
- if (pageNum > 0){
- sourceBuilder.from(pageSize * (pageNum - 1));
- } else {
- sourceBuilder.from(0);
- }
- sourceBuilder.size(pageSize);
-
- //执行查询
- SearchResponse response = executeSearch(tableName, sourceBuilder);
- SearchHits searchHits = response.getHits();
- SearchHit[] hits = searchHits.getHits();
- totalNum = searchHits.getTotalHits();
- for (int i = 0; i < hits.length; i++){
- SearchHit hit = hits[i];
- Map<String, Object> sourceMap= hit.getSourceAsMap();
- sourceMap.put("id_s", hit.getId());
- queryResult.add(sourceMap);
- }
- resultMap.put("pageList", queryResult);
- resultMap.put("totalNum", totalNum);
- resultMap.put("pageNum", pageNum);
- resultMap.put("pageSize", pageSize);
- return resultMap;
- }
-
- /**
- * @Description 查询条件组装
- * @param boolQueryBuilder
- * @param key
- * @param value
- */
- private static void queryValueBuild(BoolQueryBuilder boolQueryBuilder, String key, Object value){
- TermQueryBuilder termQueryBuilder;
- if (null != value && !"".equals(value)){
- if (value instanceof String){
- String strValue = (String) value;
- if (strValue.endsWith("%")){
- PrefixQueryBuilder prefixQueryBuilder = QueryBuilders.prefixQuery(key,strValue.replace("%",""));
- boolQueryBuilder.must(prefixQueryBuilder);
- }else if (strValue.startsWith("*") || strValue.endsWith("*")){
- MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(key, strValue.replace("*",""));
- boolQueryBuilder.must(matchQueryBuilder);
- }else {
- termQueryBuilder = QueryBuilders.termQuery(key, strValue);
- boolQueryBuilder.must(termQueryBuilder);
- }
- } else if (value instanceof Collection){
- Collection<? extends Object> collectionValue = (Collection<? extends Object>) value;
- //此处使用了多值条件
- boolQueryBuilder.must(QueryBuilders.termsQuery(key, collectionValue));
- } else {
- termQueryBuilder = QueryBuilders.termQuery(key, value);
- boolQueryBuilder.must(termQueryBuilder);
- }
- }
- }
-
- /**
- * @Description 范围条件查询组装
- * @param boolQueryBuilder
- * @param rangeCondition
- */
- private static void rangeValueBuild(BoolQueryBuilder boolQueryBuilder, Map<String, Object> rangeCondition){
- for (Map.Entry<String, Object> entry : rangeCondition.entrySet()){
- Map<String, Object> range = intervalParse((String) entry.getValue());
- String key = entry.getKey();
- RangeQueryBuilder rangeQueryBuilder;
- if (key.endsWith("_s")){
- rangeQueryBuilder = QueryBuilders.rangeQuery(key + ".keyword");
- }else {
- rangeQueryBuilder = QueryBuilders.rangeQuery(key);
- }
- if (!StringUtils.isEmpty(range.get("leftValue"))){
- if (DefineConstant.INTERVAL_OPEN_VALUE.equals(range.get("leftType"))){
- rangeQueryBuilder.from(range.get("leftValue"),false);
- } else if (DefineConstant.INTERVAL_CLOSE_VALUE.equals(range.get("leftType"))){
- rangeQueryBuilder.from(range.get("leftValue"),true);
- }
- }
- if (!StringUtils.isEmpty(range.get("rightValue"))){
- if (DefineConstant.INTERVAL_OPEN_VALUE.equals(range.get("rightType"))){
- rangeQueryBuilder.to(range.get("rightValue"),false);
- } else if (DefineConstant.INTERVAL_CLOSE_VALUE.equals(range.get("rightType"))){
- rangeQueryBuilder.to(range.get("rightValue"),true);
- }
- }
- boolQueryBuilder.must(rangeQueryBuilder);
- }
- }
-
- /**
- * @Description 区间解析:[,]/(,)/[,)/(,]
- * @param interval
- * @return
- */
- private static Map<String, Object> intervalParse(String interval){
- Map<String, Object> range = new HashMap<>();
- if (interval.startsWith(DefineConstant.INTERVAL_CLOSE_LEFT)){
- range.put("leftType", DefineConstant.INTERVAL_CLOSE_VALUE);
- } else if (interval.startsWith(DefineConstant.INTERVAL_OPEN_LEFT)){
- range.put("leftType", DefineConstant.INTERVAL_OPEN_VALUE);
- } else{
- log.error("区间参数格式错误:{}",interval);
- //若实际业务相关需要,抛出异常处理throw new Exception();
- }
- if (interval.endsWith(DefineConstant.INTERVAL_CLOSE_RIGHT)){
- range.put("rightType", DefineConstant.INTERVAL_CLOSE_VALUE);
- } else if (interval.startsWith(DefineConstant.INTERVAL_OPEN_RIGHT)){
- range.put("rightType", DefineConstant.INTERVAL_OPEN_VALUE);
- } else{
- log.error("区间参数格式错误:{}",interval);
- //若实际业务相关需要,抛出异常处理throw new Exception();
- }
- int strLen = interval.length();
- String[] lr = interval.substring(1, strLen - 1).split(DefineConstant.COMMAN_SIGN, 2);
- if (lr.length > 0){
- range.put("leftValue", lr[0]);
- }
- if (lr.length > 1){
- range.put("rightValue", lr[1]);
- }
- return range;
- }
-
- /**
- * @Description 查询排序
- * @param sourceBuilder
- * @param orderBy
- */
- private static void buildSort(SearchSourceBuilder sourceBuilder, List<String> orderBy){
- SortBuilder<FieldSortBuilder> sortBuilder;
- for (String sortField : orderBy){
- if (sortField.startsWith("-")){
- //降序排序
- if (sortField.endsWith("_s")){
- sortBuilder = SortBuilders.fieldSort(sortField.replace("-","") + ".keyword").order(SortOrder.DESC);
- } else {
- sortBuilder = SortBuilders.fieldSort(sortField.replace("-","")).order(SortOrder.DESC);
- }
- } else {
- //升序排序
- if (sortField.endsWith("_s")){
- sortBuilder = SortBuilders.fieldSort(sortField.replace("-","") + ".keyword").order(SortOrder.ASC);
- } else {
- sortBuilder = SortBuilders.fieldSort(sortField.replace("-","")).order(SortOrder.ASC);
- }
- }
- sourceBuilder.sort(sortBuilder);
- }
- }
-
- /**
- * @Description 执行查询
- * @param tableName 对应的es的index名
- * @param sourceBuilder
- * @return
- */
- private static SearchResponse executeSearch(String tableName, SearchSourceBuilder sourceBuilder){
- // 获取不同系统的换行符
- String lineSeparator = System.lineSeparator();
- log.info(lineSeparator + "index:" + tableName + lineSeparator + "search:"+ sourceBuilder.toString() + lineSeparator);
- RestHighLevelClient client = EsClient.getInstance();
- SearchRequest searchRequest = new SearchRequest(tableName);
- SearchResponse response = null;
- //设置查询的文档代表的对象的类,即type(此处我写死固定值,可以自行定义)
- searchRequest.types(DefineConstant.SEARCH_REQUEST_TYPE);
- searchRequest.source(sourceBuilder);
- try {
- response = client.search(searchRequest, RequestOptions.DEFAULT);
- log.info("search status:{}, totalNum:{}",response.status(), response.getHits().getTotalHits());
- } catch (IOException e) {
- //异常处理,实际业务中是需要根据需求具体处理,自定义异常捕获
- log.error(e.getMessage());
- }
- return response;
- }
例如查询trade_info索引中客户号为10005,交易金额在200以内(包含200)的记录,并按交易时间倒序排序查询
控制台打印以及查询结果
而通过工具查询的记录:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。