springboot集成ES,以及应用

1:引入依赖

          <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.4.2</version>
            </dependency>


            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.4.2</version>
            </dependency>

2:elasticSearch配置

elasticSearch配置

es.userName=superuser
es.password=Dxm_123
es.host=10.157.24.122
es.port=8200

3:ES的配置

@Configuration
public class ElasticSearchConfig {

    @Value("${es.userName}")
    private String userName;

    @Value("${es.password}")
    private String password;

    @Value("${es.host}")
    private String esHost;

    @Value("${es.port}")
    private Integer esPort;

    @Bean
    public RestHighLevelClient esRestClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));


        RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, esPort))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;

    }
}

4:ES服务的接口

package com.dxm.insur.bi.biz.es;

import java.util.List;
import java.util.Map;

/**
 * Created by huxiaona on 2020-10-12
 **/
public interface ElasticSearchService {

    /**
     * json形式存储doc
     * @param index
     * @param docJsonString
     * @param id
     */
    void saveDoc(String index, String docJsonString, String id);

    /**
     * es搜索
     * @param index
     * @param where  范围查询对应Object为map且对应的key值分别为start和end
     *               or查询对应的Object为Set,且是模糊匹配
     *               in查询对应的Object为List
     *               否则为单个精准匹配
     * @param sortFieldsToAsc
     * @param includeFields
     * @param excludeFields
     * @param timeOut
     * @return
     */
    List<Map<String, Object>> search(String index, Map<String, Object> where, Map<String, Boolean> sortFieldsToAsc, String[] includeFields, String[] excludeFields, int timeOut, String collapseFields);
}

5:ES服务的具体实现

package com.dxm.insur.bi.biz.es.impl;

import com.dxm.insur.bi.base.exception.InsureEtlException;
import com.dxm.insur.bi.base.exception.InsureEtlResponseCode;
import com.dxm.insur.bi.base.util.StringUtil;
import com.dxm.insur.bi.biz.es.ElasticSearchService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by huxiaona on 2020-10-12
 **/
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    public static final Logger logger = LoggerFactory.getLogger(ElasticSearchService.class);


    @Autowired
    private RestHighLevelClient highLevelClient;

    @Override
    public void saveDoc(String index, String doc, String id) {
        try {
            IndexRequest indexRequest = new IndexRequest(index).id(id).source(doc, XContentType.JSON);
            IndexResponse indexResponse = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            logger.info("[ElasticSearchService] save doc of index:{} success, response:{}!", index, indexResponse);
        } catch (Exception e) {
            logger.error("[ElasticSearchService] save doc:{} of index:{} error", doc, index, e);
            throw new InsureEtlException(InsureEtlResponseCode.ES_SAVE_DOC_ERROR);
        }
    }

    @Override
    public List<Map<String, Object>> search(String index, Map<String, Object> where, Map<String, Boolean> sortFieldsToAsc, String[] includeFields, String[] excludeFields,int timeOut, String collapseField) {
        SearchResponse searchResponse = null;
        logger.info("[ElasticSearchService]search of index:{} begin", index);
        try {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 构造条件
            if(where != null && !CollectionUtils.isEmpty(where)) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                where.forEach((k, v) -> {
                    // 范围查询或者 or 查询
                    if (v instanceof Map && v != null) {
                        // 包含start和end则为范围查询
                        Map<String, String> mapV = (Map<String, String>) v;
                        if (mapV.containsKey("start") && mapV.containsKey("end")) {
                            boolQueryBuilder.must(QueryBuilders.rangeQuery(k).
                                    gte(mapV.get("start")).
                                    lte(mapV.get("end")));
                        }
                    } else if (v instanceof Set && v != null) {
                        // or 查询
                        BoolQueryBuilder orQueryBuilder = QueryBuilders.boolQuery();
                        ((Set) v).forEach(value -> {
                            orQueryBuilder.should(QueryBuilders.wildcardQuery(k, value.toString()));
                        });
                        boolQueryBuilder.must(orQueryBuilder);
                    } else if (v instanceof List && v != null) {
                        // in查询
                        boolQueryBuilder.must(QueryBuilders.termsQuery(k, (List<String>)v));
                    } else {
                        // 模糊匹配
                        boolQueryBuilder.must(QueryBuilders.termQuery(k, v.toString()));
                    }
                });
                sourceBuilder.query(boolQueryBuilder);
            }
            sourceBuilder.timeout(new TimeValue(timeOut, TimeUnit.SECONDS));
            if (sortFieldsToAsc != null && !sortFieldsToAsc.isEmpty()) {
                sortFieldsToAsc.forEach((k, v) -> {
                    sourceBuilder.sort(new FieldSortBuilder(k).order(v ? SortOrder.ASC : SortOrder.DESC));
                });
            }
            // 指定字段去重折叠
            if (!StringUtil.isBlank(collapseField)) {
                sourceBuilder.collapse(new CollapseBuilder(collapseField));
            }
            sourceBuilder.size(10000);
            sourceBuilder.fetchSource(includeFields, excludeFields);
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);
            searchRequest.source(sourceBuilder);
            logger.info("[ElasticSearchService] search source:{}", searchRequest.source().toString());
            searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            logger.info("[ElasticSearchService] search response:{}", searchResponse);

        } catch (Exception e) {
            logger.error("[ElasticSearchService] search error!", e);
            throw new InsureEtlException(InsureEtlResponseCode.ES_QUERY_ERROR);
        }

        //解析返回
        if (searchResponse.status() != RestStatus.OK) {
            logger.error("[ElasticSearchService] search error!");
            throw new InsureEtlException(InsureEtlResponseCode.ES_QUERY_ERROR);
        }
        if (searchResponse.getHits().getTotalHits().value <= 0) {
            logger.info("[ElasticSearchService] search res is empty, return!");
            return Collections.emptyList();
        }
        return Arrays.stream(searchResponse.getHits().getHits()).map(b -> {
              return b.getSourceAsMap();
        }).collect(Collectors.toList());
    }
}

7:实际查询应用

        // 组装查询条件
        Map<String, Object> where = new HashMap<>();
        where.put("eventDate", request.getDate());
        if(!StringUtils.isEmpty(request.getItemId())) {
            where.put("itemId", request.getItemId());
        }
        where.put("passId", request.getUserInfos());
        String[] includeFields = {"uaId"};

        StopWatch clock = new StopWatch();
        clock.start();
        List<Map<String, Object>> searchRes = elasticSearchService.search(CommonConstants.ES_H5_LOG_INDEX, where, null, includeFields, null, CommonConstants.ES_SEARCH_LIMIT_TIME, "uaId");
        clock.stop();
        long handlingTime1 = clock.getTime();
        logger.info("--------------精确查找, 耗时: " + handlingTime1 + "ms");


       // passId条件改为uaId
        where.remove("passId");
        where.put("uaId", new ArrayList<String>(uaIds));
        List<String> spms = Splitter.on(",").splitToList(AppConfigUtil.getProperty(AppConfigConstants.USER_TRACK_SPM));
        where.put("spm", new HashSet<>(spms));
        Map<String, Boolean> sortFieldsToAsc = new HashMap<>();
        sortFieldsToAsc.put("sessionId", true);
        sortFieldsToAsc.put("requesttime", true);
        includeFields = new String[]{"sessionId", "requesttime", "spm"};

        clock.start();
        searchRes = elasticSearchService.search(CommonConstants.ES_H5_LOG_INDEX, where, sortFieldsToAsc, includeFields, null, CommonConstants.ES_SEARCH_LIMIT_TIME, null);
        clock.stop();
        long handlingTime2 = clock.getTime();
        logger.info("--------------模糊查找, 耗时: " + handlingTime2 + "ms");

8:存储的bean

package com.dxm.insur.bi.biz.log.bean;

import lombok.Data;

import java.util.Map;

/**
 * Created by huxiaona on 2020-10-08
 **/
@Data
public class InsurH5Log {

    private String eventDate;

    private String requesttime;

    private String sessionId;

    private String uaId;

    private String passId;

    private String channelId;

    private String customerId;

    private String userId;

    private Long itemId;

    private String spm;

    private String prespm;

    private String eventTag;

    private String preeventTag;

    private Integer from;

    private String refer;

    private String activityId;

    private Map<String, String> extendParam;

    private String ua;

    private Map<String, String> apiParams;
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,047评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,807评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,501评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,839评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,951评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,117评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,188评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,929评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,372评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,679评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,837评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,536评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,168评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,886评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,129评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,665评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,739评论 2 351

推荐阅读更多精彩内容