美文网首页
基于spring boot的elasticsearch Rest

基于spring boot的elasticsearch Rest

作者: Tristan_Feng | 来源:发表于2019-01-01 16:00 被阅读0次

    由于工作中使用到了elasticsearch,现将工作中的代码贴出来,请大家指教
    1、application.yml中配置elasticsearch节点信息:

    elkconfig:
      clustername: test
      index: test122
      hosts:
        -
          ip: 192.168.1.2
          port: 9200
          schema: http
        -
          ip: 192.168.1.3
          port: 9200
          schema: http
        -
          ip: 192.168.1.4
          port: 9200
          schema: http
    

    2、配置elasticsearch配置类

    @Data
    @ConfigurationProperties(prefix = "elkconfig")
    @Configuration
    public class ElkConfig {
        private String clustername;
        private String index;
        @NestedConfigurationProperty
        private List<Hosts> hosts;
    }
    

    3、单例模式实现RestHighLevelClient

    @Component
    public class ESRestClient {
    
        private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ESRestClient.class);
    
        @Autowired
        private ElkConfig elkConfig;
    
        private static ESRestClient restClientUtil;
    
        private static RestHighLevelClient client = null;
    
        @PostConstruct
        public void init() {
            restClientUtil = this;
            restClientUtil.elkConfig = this.elkConfig;
        }
    
        public RestHighLevelClient getClient(){
            if(client != null){
                return client;
            }else {
                synchronized(ESRestClient.class) {
                    /* client = new RestHighLevelClient(clientBuilder);*/
                    HttpHost[] httpHosts = new HttpHost[restClientUtil.elkConfig.getHosts().size()];
                    for (int i = 0; i<httpHosts.length;i++){
                        Hosts host = restClientUtil.elkConfig.getHosts().get(i);
                        httpHosts[i] = new HttpHost(host.getIp(),Integer.parseInt(host.getPort()),host.getSchema());
                    }
                    RestClientBuilder clientBuilder = RestClient.builder(httpHosts);
                    client = new RestHighLevelClient(clientBuilder);
                    logger.info("RestClientUtil intfo create rest high level client successful!");
                    return client;
                }
            }
        }
    
    
    }
    

    4、新建elasticservice供调用

    @Component
    public class ElasticSearchService {
    
        private static final Logger logger = LoggerFactory.getLogger(ElasticSearchService.class);
    
        @Autowired
        private ESRestClient esRestClient;
    
        @Autowired
        private ElkConfig elkConfig;
    
        /**
         * 根据布尔条件进行查询
         * @param boolQueryBuilder
         * @return
         */
        public SearchResponse searchMessage(BoolQueryBuilder boolQueryBuilder) {
            try {
                RestHighLevelClient restClient = esRestClient.getClient();
                SearchRequest searchRequest = new SearchRequest(elkConfig.getIndex());
    
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.size(100);
                sourceBuilder.query(boolQueryBuilder);
                logger.info(sourceBuilder.toString());
                searchRequest.source(sourceBuilder);
                SearchResponse searchResponse = restClient.search(searchRequest);
                searchResponse.getHits().forEach(message -> {
                    try {
                        String sourceAsString = message.getSourceAsString();
                        logger.info(sourceAsString);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                return searchResponse;
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Couldn't get Detail");
            }
        }
    
        /**
         * 单条件检索
         * @param fieldKey
         * @param fieldValue
         * @return
         */
        public MatchPhraseQueryBuilder uniqueMatchQuery(String fieldKey,String fieldValue){
            MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(fieldKey,fieldValue);
            return matchPhraseQueryBuilder;
        }
    
        /**
         * 多条件检索并集,适用于搜索比如包含腾讯大王卡,滴滴大王卡的用户
         * @param fieldKey
         * @param queryList
         * @return
         */
        public BoolQueryBuilder orMatchUnionWithList(String fieldKey,List<String> queryList){
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            for (String fieldValue : queryList){
                boolQueryBuilder.should(QueryBuilders.matchPhraseQuery(fieldKey,fieldValue));
            }
            return boolQueryBuilder;
        }
    
        /**
         * 范围查询,左右都是闭集
         * @param fieldKey
         * @param start
         * @param end
         * @return
         */
        public RangeQueryBuilder rangeMathQuery(String fieldKey,String start,String end){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(fieldKey);
            rangeQueryBuilder.gte(start);
            rangeQueryBuilder.lte(end);
            return rangeQueryBuilder;
        }
    
        /**
         * 根据中文分词进行查询
         * @param fieldKey
         * @param fieldValue
         * @return
         */
        public MatchQueryBuilder matchQueryBuilder(String fieldKey,String fieldValue){
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(fieldKey,fieldValue).analyzer("ik_smart");
            return matchQueryBuilder;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:基于spring boot的elasticsearch Rest

          本文链接:https://www.haomeiwen.com/subject/yzbnlqtx.html