package com.topwalk.analysis.es.operation.impl; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import org.apache.log4j.Logger; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkProcessor.Listener; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.count.CountRequestBuilder; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.deletebyquery.DeleteByQueryRequestBuilder; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; 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.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.stats.Stats; import org.elasticsearch.search.aggregations.metrics.sum.Sum; import org.elasticsearch.search.sort.SortOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.topwalk.analysis.es.configuration.EsAggregation; import com.topwalk.analysis.es.configuration.EsAggregationParams; import com.topwalk.analysis.es.configuration.EsQueryParam; import com.topwalk.analysis.es.configuration.LogicOperator; import com.topwalk.analysis.es.configuration.Operator; import com.topwalk.analysis.es.configuration.Pager; import com.topwalk.analysis.es.factory.EsClient; import com.topwalk.analysis.es.operation.intf.EsService; public class EsServiceImpl implements EsService{ private Logger logger = Logger.getLogger(EsServiceImpl.class); @Override public boolean indexDataById(Client client, String index, String type, String id, String data) { // TODO Auto-generated method stub IndexResponse response = null; try { response = client.prepareIndex(index, type, id).setSource(data).execute().actionGet(); } catch (Exception e) { e.printStackTrace(); return false; } return response.isCreated(); } @Override public boolean bulkindexData(Client client, String index, String type, String data) { // TODO Auto-generated method stub BulkRequestBuilder bulkRequest = client.prepareBulk(); JSONArray arry = JSON.parseArray(data); for(int i = 0; i < arry.size(); i++) { JSONObject jobj = JSON.parseObject(arry.getString(i)); if(jobj.containsKey("_id")) { String _id = jobj.getString("_id"); jobj.remove("_id"); bulkRequest.add(client.prepareIndex(index, type, _id).setSource(arry.getString(i)) ); } else { bulkRequest.add(client.prepareIndex(index, type).setSource(arry.getString(i)) ); } } BulkResponse bulkResponse = bulkRequest.execute().actionGet(); if(bulkResponse.hasFailures()) { logger.error("bulkinsert fail message...." + bulkResponse.buildFailureMessage()); return false; } else { return true; } } @Override public boolean bulkupdateData(Client client, String index, String type, String data, List<EsQueryParam> params) { // TODO Auto-generated method stub List<String> types = new ArrayList<String>(); types.add(type); EsServiceImpl esimpl = new EsServiceImpl(); Pager page = new Pager(); page.setFrom(0); int count = esimpl.getCountByFields(client, index, types, params); page.setNum(count); List<String> ids = esimpl.getIdByFields(client, index, type, params, page); if(ids.size() == 0 || count == 0) { return false; } Map<String, Object> fieldValue = (Map<String, Object>) JSON.parse(data); for (String id : ids ) { esimpl.updateIndexById(client, index, type, id, fieldValue); } return true; } @Override public boolean indexData(Client client, String index, String type, String data) { // TODO Auto-generated method stub IndexResponse response = null; try { response = client.prepareIndex(index, type).setSource(data).execute().actionGet(); } catch (Exception e) { e.printStackTrace(); return false; } return response.isCreated(); } @Override public String getIndexById(Client client, String index, String type, String id) { // TODO Auto-generated method stub GetResponse response = null ; String result = null; try { response = client.prepareGet(index, type, id).execute().actionGet(); result = response.getSourceAsString(); } catch (Exception e ) { e.printStackTrace(); } return result; } @Override public boolean isIndexExists(Client client, String index, String type, String id) { // TODO Auto-generated method stub GetResponse response = null ; boolean result = false; try { response = client.prepareGet(index, type, id).execute().actionGet(); result = response.isExists(); } catch (Exception e ) { e.printStackTrace(); return false; } return result; } @Override public boolean delIndexById(Client client, String index, String type, String id) { // TODO Auto-generated method stub DeleteResponse response = null ; boolean result = false; try { response = client.prepareDelete(index, type, id).execute().actionGet(); result = response.isFound(); } catch (Exception e ) { e.printStackTrace(); return result; } return result; } @Override public boolean delIndexByFields(Client client, String index, String type, List<EsQueryParam> params) { // TODO Auto-generated method stub BoolQueryBuilder db = QueryBuilders.boolQuery(); try { DeleteByQueryRequestBuilder dbq = client.prepareDeleteByQuery(index).setTypes(type); db = getQueryBuilder(params); dbq.setQuery(db); dbq.execute().actionGet(); } catch (Exception e ) { e.printStackTrace(); return true; } return true; } @Override public boolean updateIndexById(Client client, String index, String type, String id, Map<String, Object> fieldValue) { UpdateResponse response = null; UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index(index); if(type != null) { updateRequest.type(type); } updateRequest.id(id); updateRequest.doc(fieldValue); updateRequest.retryOnConflict(5); try { response = client.update(updateRequest).get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } @Override public boolean addFieldToDoc(Client client, String index, String type, String id, Map<String, Object> fieldValue) { // TODO Auto-generated method stub Iterator<String> iter = fieldValue.keySet().iterator(); boolean isExist = false; while (iter.hasNext()) { String key = iter.next(); isExist = isFieldExist(client, index, type, id, key); if(isExist) { try { throw new Exception("the key [" + key + "] is exist!"); } catch (Exception e) { e.printStackTrace(); return false; } } } UpdateResponse response = null; UpdateRequest updateRequest = new UpdateRequest(); updateRequest.index(index).type(type).id(id); updateRequest.doc(fieldValue); try { response = client.update(updateRequest).get(); } catch (InterruptedException e) { e.printStackTrace(); return false; } catch (ExecutionException e) { e.printStackTrace(); return false; } return true; } @Override public boolean removeieldFromDoc(Client client, String index, String type, String id, String field) { boolean isExist = false; isExist = isFieldExist( client, index, type, id, field); if(! isExist) { try { throw new Exception("the key [" + field + "] is not exist!"); } catch (Exception e) { e.printStackTrace(); return false; } } try { client.prepareUpdate(index, type, id).setScript("ctx._source.remove(\"" + field+ "\")", ScriptService.ScriptType.INLINE).execute().actionGet(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public List<String> getIdByFields(Client client, String index, String type, List<EsQueryParam> params, Pager pager) { BoolQueryBuilder db = QueryBuilders.boolQuery(); List<String> list= new ArrayList<String>(); SearchRequestBuilder searchRequest = null; db = getQueryBuilder(params); if (params != null && params.size() > 0 ) { searchRequest = client.prepareSearch(index).setQuery(db).setTypes(type); } else { searchRequest = client.prepareSearch(index).setQuery(QueryBuilders.matchAllQuery()).setTypes(type); } if(pager != null && pager.getFrom() >= 0 && pager.getNum() > 0 ) { searchRequest.setFrom(pager.getFrom()).setSize(pager.getNum()); } else if(pager != null && pager.getSortField() != null && pager.getSortValue().equals( "ASC")) { searchRequest.addSort(pager.getSortField(), SortOrder.ASC); } else if(pager != null && pager.getSortField() != null && pager.getSortValue().equals("desc")) { searchRequest.addSort(pager.getSortField(), SortOrder.DESC); } SearchResponse response = searchRequest.execute().actionGet(); for(SearchHit hit : response.getHits()) { list.add(hit.getId()); } return list; } @Override public List<String> getIndexByFields(Client client, String index, List<String> types, List<EsQueryParam> params, Pager pager) { BoolQueryBuilder db = QueryBuilders.boolQuery(); List<String> list= new ArrayList<String>(); try { SearchRequestBuilder searchRequest = null; if (params != null && params.size() > 0 ) { db = getQueryBuilder(params); searchRequest = client.prepareSearch(index).setQuery(db); } else { searchRequest = client.prepareSearch(index).setQuery(QueryBuilders.matchAllQuery()); } if(pager != null && pager.getFrom() >= 0 && pager.getNum() > 0 ) { searchRequest.setFrom(pager.getFrom()).setSize(pager.getNum()); } else if(pager != null && pager.getSortField() != null && pager.getSortValue().equals("asc")) { searchRequest.addSort(pager.getSortField(), SortOrder.ASC); } else if(pager != null && pager.getSortField() != null && pager.getSortValue().equals("desc")) { searchRequest.addSort(pager.getSortField(), SortOrder.DESC); } if(types != null && types.size() > 0) { String[] a = new String[types.size()]; searchRequest.setTypes(types.toArray(a)); } SearchResponse response = searchRequest.execute().actionGet(); if(response.getHits().totalHits() > 0) { for(SearchHit hit : response.getHits()) { list.add(JSON.toJSONString(hit.getSource())); } } } catch (Exception e) { e.printStackTrace(); } return list; } @Override public List<String> scrollSearch(Client client, String index, String type, List<EsQueryParam> params, Pager pager) { BoolQueryBuilder db = QueryBuilders.boolQuery(); List<String> list= new ArrayList<String>(); try { SearchRequestBuilder searchRequest = null; if (params != null && params.size() > 0 ) { db = getQueryBuilder(params); searchRequest = client.prepareSearch(index).setSearchType(SearchType.SCAN).setScroll(new TimeValue(60000)).setQuery(db); } else { searchRequest = client.prepareSearch(index).setSearchType(SearchType.SCAN).setScroll(new TimeValue(60000)).setQuery(QueryBuilders.matchAllQuery()); } if (type != null) { searchRequest.setTypes(type); } if(pager != null) { searchRequest.setSize(pager.getNum()); } SearchResponse scrollResp = searchRequest.execute().actionGet(); while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet(); if(scrollResp.getHits().getHits().length == 0) { break; } for(SearchHit hit: scrollResp.getHits()) { list.add(hit.getSourceAsString()); } } } catch(Exception e) { e.printStackTrace(); } return list; } @Override public boolean reindex(Client client, String index, String type,String newindex, String newtype, List<EsQueryParam> params) { BoolQueryBuilder db = QueryBuilders.boolQuery(); try { SearchRequestBuilder searchRequest = null; if (params != null && params.size() > 0 ) { db = getQueryBuilder(params); searchRequest = client.prepareSearch(index).setSearchType(SearchType.SCAN).setScroll(new TimeValue(60000)).setQuery(db); } else { searchRequest = client.prepareSearch(index).setSearchType(SearchType.SCAN).setScroll(new TimeValue(60000)).setQuery(QueryBuilders.matchAllQuery()); } if (type != null) { searchRequest.setTypes(type); } SearchResponse scrollResp = searchRequest.execute().actionGet(); BulkProcessor bulkProcessor = BulkProcessor.builder(client, createBulkProcessorListener()) .setBulkActions(10000) .setFlushInterval(TimeValue.timeValueSeconds(5)).build(); while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet(); if(scrollResp.getHits().getHits().length == 0) { bulkProcessor.close(); break; } for(SearchHit hit: scrollResp.getHits()) { IndexRequest request = new IndexRequest(newindex, newtype, hit.id()); request.source(hit.getSourceAsString()); bulkProcessor.add(request); } bulkProcessor.flush(); } } catch(Exception e) { e.printStackTrace(); return false; } return true; } public Map<String, Object> getMappings(Client client, String index, String type) { Map<String, Object> result = null; IndexMetaData imd = null; try { ClusterState cs = client.admin() .cluster() .prepareState() .setIndices(index) .execute() .actionGet() .getState(); imd = cs.getMetaData().index(index); MappingMetaData mdd = imd.mapping(type); result = mdd.getSourceAsMap(); } catch (IndexMissingException | IOException e) { } return result; } public Listener createBulkProcessorListener() { return new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { // TODO Auto-generated method stub } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { // TODO Auto-generated method stub } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { // TODO Auto-generated method stub } }; } @Override public int getCountByFields(Client client, String index, List<String> types, List<EsQueryParam> params) { CountResponse response = null; CountRequestBuilder countBuilder = null; BoolQueryBuilder db = null; try { db = getQueryBuilder(params); countBuilder = client.prepareCount(index); if(types != null && types.size() > 0) { String[] a = new String[types.size()]; countBuilder.setTypes(types.toArray(a)); } if (params != null && params.size() > 0) { response = countBuilder.setQuery(db).execute().actionGet(); } else { response = countBuilder.setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); } } catch (Exception e) { e.printStackTrace(); } return (int) response.getCount(); } //check field isexist public boolean isFieldExist(Client client, String index, String type, String id, String key) { GetResponse response = null ; boolean result = false; try { response = client.prepareGet(index, type, id).execute().actionGet(); result = JSON.parseObject(response.getSourceAsString()).containsKey(key); } catch (Exception e ) { e.printStackTrace(); } return result; } @Override public int getTermsCountByAgg(Client client, String index, List<String> types, List<EsQueryParam> params, List<EsAggregationParams> aggList, Pager page) { BoolQueryBuilder db = null; if(params != null) { db = getQueryBuilder(params); } List<Map<String, String>> result = new ArrayList<Map<String, String>>(); AbstractAggregationBuilder parentBuilder = null; for (int i = aggList.size()-1; i >= 0; i--) { EsAggregationParams aggParams = aggList.get(i); if(i == aggList.size()-1) { if (aggParams.getEsAggregation() == EsAggregation.TERM) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(page.getNum()); } } else { if (aggParams.getEsAggregation() == EsAggregation.TERM) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(page.getNum()).subAggregation(parentBuilder); } } } SearchRequestBuilder requestBuilder = client.prepareSearch(index); if(types != null && types.size() > 0) { String[] a = new String[types.size()]; requestBuilder.setTypes(types.toArray(a)); } requestBuilder.addAggregation(parentBuilder); if(db != null) { requestBuilder.setQuery(db); } SearchResponse sr = requestBuilder.execute().actionGet(); Terms t = sr.getAggregations().get(aggList.get(0).getAggName()); Iterator< ? extends MultiBucketsAggregation.Bucket > topBucket = null; topBucket = t.getBuckets().iterator(); result = getMap(topBucket, aggList, 0, result, null); return result.size(); } @Override public List<Map<String, String>> AggregationByFields(Client client, String index, List<String> types, List<EsQueryParam> params, List<EsAggregationParams> aggList) { BoolQueryBuilder db = null; if(params != null && params.size() > 0) { db = getQueryBuilder(params); } List<Map<String, String>> result = new ArrayList<Map<String, String>>(); AbstractAggregationBuilder parentBuilder = null; for (int i = aggList.size()-1; i >= 0; i--) { EsAggregationParams aggParams = aggList.get(i); if(i == aggList.size()-1) { if (aggParams.getEsAggregation() == EsAggregation.STATS) { parentBuilder = AggregationBuilders.stats( aggParams.getAggName()) .field(aggParams.getField()); } else if (aggParams.getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = DateHistogram.Order.KEY_ASC; } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = DateHistogram.Order.KEY_DESC; }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = DateHistogram.Order.COUNT_ASC; } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = DateHistogram.Order.COUNT_DESC; } parentBuilder = AggregationBuilders.dateHistogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getDateInterval()).order(order); } else if (aggParams.getEsAggregation() == EsAggregation.TERM) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null && aggParams.isValOrder() == null) { if (aggParams.getAggSize() == 0) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()); } } else { if (aggParams.getAggSize() == 0) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).order(order); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).order(order); } } } else if (aggParams.getEsAggregation() == EsAggregation.TERM_SCRIPTS) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null || aggParams.isValOrder() == null) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).order(order); } } else if (aggParams.getEsAggregation() == EsAggregation.HISTOGRAM) { parentBuilder = AggregationBuilders.histogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getHisaggrateInterval()); } else if (aggParams.getEsAggregation() == EsAggregation.SUM) { parentBuilder = AggregationBuilders.sum(aggParams.getAggName()).field(aggParams.getField()); } } else { if (aggParams.getEsAggregation() == EsAggregation.TERM) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null && aggParams.isValOrder() == null) { if (aggParams.getAggSize() == 0 ) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).subAggregation(parentBuilder); } } else { if (aggParams.getAggSize() == 0 ) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).order(order).size(aggParams.getAggSize()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).order(order).size(aggParams.getAggSize()).subAggregation(parentBuilder); } } } else if (aggParams.getEsAggregation() == EsAggregation.TERM_SCRIPTS) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null || aggParams.isValOrder() == null) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).order(order).subAggregation(parentBuilder); } } else if (aggParams.getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = DateHistogram.Order.KEY_ASC; } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = DateHistogram.Order.KEY_DESC; }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = DateHistogram.Order.COUNT_ASC; } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = DateHistogram.Order.COUNT_DESC; } parentBuilder = AggregationBuilders.dateHistogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getDateInterval()).subAggregation(parentBuilder).order(order); } else if (aggParams.getEsAggregation() == EsAggregation.HISTOGRAM) { parentBuilder = AggregationBuilders.histogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getHisaggrateInterval()).subAggregation(parentBuilder); } } } SearchRequestBuilder requestBuilder = client.prepareSearch(index); if(types != null && types.size() > 0) { String[] a = new String[types.size()]; requestBuilder.setTypes(types.toArray(a)); } requestBuilder.addAggregation(parentBuilder); if(db != null) { requestBuilder.setQuery(db); } logger.debug(requestBuilder.toString()); SearchResponse sr = requestBuilder.execute().actionGet(); Iterator< ? extends MultiBucketsAggregation.Bucket > topBucket = null; if(aggList.get(0).getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram agg = sr.getAggregations().get(aggList.get(0).getAggName()); topBucket = agg.getBuckets().iterator(); } else if (aggList.get(0).getEsAggregation() == EsAggregation.TERM ||aggList.get(0).getEsAggregation() == EsAggregation.TERM_SCRIPTS ) { Terms t = sr.getAggregations().get(aggList.get(0).getAggName()); topBucket = t.getBuckets().iterator(); } else if (aggList.get(0).getEsAggregation() == EsAggregation.HISTOGRAM) { Histogram agg = sr.getAggregations().get(aggList.get(0).getAggName()); topBucket = agg.getBuckets().iterator(); } else if (aggList.get(0).getEsAggregation() == EsAggregation.SUM) { Sum agg = sr.getAggregations().get(aggList.get(0).getAggName()); Map<String, String> sumresult = new HashMap<String, String>(); sumresult.put(agg.getName(), String.valueOf(agg.getValue())); result.add(sumresult); return result; } else if(aggList.get(0).getEsAggregation() == EsAggregation.STATS) { Stats stats = sr.getAggregations().get(aggList.get(0).getAggName()); Map<String, String> statsresult = new HashMap<String, String>(); statsresult.put("count", String.valueOf(stats.getCount())); statsresult.put("avg", String.valueOf(stats.getAvg())); statsresult.put("max", String.valueOf(stats.getMax())); statsresult.put("min", String.valueOf(stats.getMin())); statsresult.put("sum", String.valueOf(stats.getSum())); result.add(statsresult); return result; } Map<String, String> map = new HashMap<String, String>(); result = getMap(topBucket, aggList, 0, result, map); return result; } @Override public SearchResponse getResponseByAggregationField(Client client, String index, List<String> types, List<EsQueryParam> params, List<EsAggregationParams> aggList) { BoolQueryBuilder db = null; if(params != null && params.size() > 0) { db = getQueryBuilder(params); } List<Map<String, String>> result = new ArrayList<Map<String, String>>(); AbstractAggregationBuilder parentBuilder = null; for (int i = aggList.size()-1; i >= 0; i--) { EsAggregationParams aggParams = aggList.get(i); if(i == aggList.size()-1) { if (aggParams.getEsAggregation() == EsAggregation.STATS) { parentBuilder = AggregationBuilders.stats( aggParams.getAggName()) .field(aggParams.getField()); } else if (aggParams.getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = DateHistogram.Order.KEY_ASC; } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = DateHistogram.Order.KEY_DESC; }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = DateHistogram.Order.COUNT_ASC; } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = DateHistogram.Order.COUNT_DESC; } parentBuilder = AggregationBuilders.dateHistogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getDateInterval()).order(order); } else if (aggParams.getEsAggregation() == EsAggregation.TERM) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null && aggParams.isValOrder() == null) { if (aggParams.getAggSize() == 0) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()); } } else { if (aggParams.getAggSize() == 0) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).order(order); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).order(order); } } } else if (aggParams.getEsAggregation() == EsAggregation.TERM_SCRIPTS) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null || aggParams.isValOrder() == null) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).order(order); } } else if (aggParams.getEsAggregation() == EsAggregation.HISTOGRAM) { parentBuilder = AggregationBuilders.histogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getHisaggrateInterval()); } else if (aggParams.getEsAggregation() == EsAggregation.SUM) { parentBuilder = AggregationBuilders.sum(aggParams.getAggName()).field(aggParams.getField()); } else if (aggParams.getEsAggregation() == EsAggregation.SUM_SCRIPTS) { parentBuilder = AggregationBuilders.sum(aggParams.getAggName()).script(aggParams.getField()); } } else { if (aggParams.getEsAggregation() == EsAggregation.TERM) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null && aggParams.isValOrder() == null) { if (aggParams.getAggSize() == 0 ) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).size(aggParams.getAggSize()).subAggregation(parentBuilder); } } else { if (aggParams.getAggSize() == 0 ) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).order(order).size(aggParams.getAggSize()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).field(aggParams.getField()).order(order).size(aggParams.getAggSize()).subAggregation(parentBuilder); } } } else if (aggParams.getEsAggregation() == EsAggregation.TERM_SCRIPTS) { Terms.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = Terms.Order.term(true); } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = Terms.Order.term(false); }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = Terms.Order.count(true); } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = Terms.Order.count(false); } if( aggParams.isKeyOrder() == null || aggParams.isValOrder() == null) { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).subAggregation(parentBuilder); } else { parentBuilder = AggregationBuilders.terms(aggParams.getAggName()).script(aggParams.getField()).order(order).subAggregation(parentBuilder); } } else if (aggParams.getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram.Order order = null; if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("asc")) { order = DateHistogram.Order.KEY_ASC; } else if( aggParams.isKeyOrder() !=null && aggParams.isKeyOrder().equals("desc") ) { order = DateHistogram.Order.KEY_DESC; }else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("asc") ) { order = DateHistogram.Order.COUNT_ASC; } else if( aggParams.isValOrder() !=null && aggParams.isValOrder().equals("desc") ){ order = DateHistogram.Order.COUNT_DESC; } parentBuilder = AggregationBuilders.dateHistogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getDateInterval()).subAggregation(parentBuilder).order(order); } else if (aggParams.getEsAggregation() == EsAggregation.HISTOGRAM) { parentBuilder = AggregationBuilders.histogram(aggParams.getAggName()).field(aggParams.getField()).interval(aggParams.getHisaggrateInterval()).subAggregation(parentBuilder); } } } SearchRequestBuilder requestBuilder = client.prepareSearch(index); if(types != null && types.size() > 0) { String[] a = new String[types.size()]; requestBuilder.setTypes(types.toArray(a)); } requestBuilder.addAggregation(parentBuilder); if(db != null) { requestBuilder.setQuery(db); } System.out.println(requestBuilder.toString()); SearchResponse sr = requestBuilder.execute().actionGet(); return sr; } public List<Map<String, String>> getMap(Iterator< ? extends MultiBucketsAggregation.Bucket > topBucket , List<EsAggregationParams> aggList, int level, List<Map<String, String>> result, Map<String, String> map) { if (aggList.size() ==1&& level == 0) { while(topBucket.hasNext()) { map = new HashMap<String, String>(); MultiBucketsAggregation.Bucket b3= topBucket.next(); if (aggList.get(0).getEsAggregation() == EsAggregation.TERM_SCRIPTS) { map.put( b3.getKey(), String.valueOf(b3.getDocCount()) ); } else { map.put(aggList.get(0).getField(), b3.getKey()); map.put("doc_count", String.valueOf(b3.getDocCount())); } result.add(map); } return result; } else { level ++; } if(level < aggList.size() && aggList.size() != 1) { while(topBucket.hasNext()) { Map<String, String> map2 = new HashMap<String, String>(); MultiBucketsAggregation.Bucket b2= topBucket.next(); map2.put(aggList.get(level-1).getField(), b2.getKey()); map2.put("doc_count" , String.valueOf(b2.getDocCount()) ); if(aggList.get(level).getEsAggregation() == EsAggregation.TERM || aggList.get(level).getEsAggregation() == EsAggregation.TERM_SCRIPTS) { Terms t = b2.getAggregations().get(aggList.get(level ).getAggName()); map2.put(aggList.get(level).getField(), b2.getKey()); getMap(t.getBuckets().iterator(), aggList, level, result, map2); } else if (aggList.get(level).getEsAggregation() == EsAggregation.STATS) { Stats stats = b2.getAggregations().get(aggList.get(level ).getAggName()); map2.put("count", String.valueOf(stats.getCount())); map2.put("sum", String.valueOf(stats.getSum())); map2.put("avg", String.valueOf(stats.getAvg())); map2.put("max", String.valueOf(stats.getMax())); map2.put("min", String.valueOf(stats.getMin())); result.add(map2); } else if (aggList.get(level).getEsAggregation() == EsAggregation.SUM) { Sum agg = b2.getAggregations().get(aggList.get(level).getAggName()); map2.put(aggList.get(level ).getField(), String.valueOf(agg.getValue())); result.add(map2); } else if (aggList.get(level).getEsAggregation() == EsAggregation.DATE_HISTOGRAM) { DateHistogram datehis = b2.getAggregations().get(aggList.get(level ).getAggName()); map2.put(aggList.get(level ).getField(), b2.getKey()); getMap( datehis.getBuckets().iterator(), aggList, level, result, map2); } else if (aggList.get(level).getEsAggregation() == EsAggregation.HISTOGRAM) { Histogram his = b2.getAggregations().get(aggList.get(level ).getAggName()); map2.put(aggList.get(level ).getField(), b2.getKey()); getMap( his.getBuckets().iterator(), aggList, level, result, map2); } } return result; } else { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); //List<String> list = new ArrayList<String>(); while(topBucket.hasNext()) { Map<String, String> m = new HashMap<String, String>(); MultiBucketsAggregation.Bucket b3= topBucket.next(); m.put(aggList.get(level -1 ).getField(), b3.getKey()); m.put("doc_count", String.valueOf(b3.getDocCount())); list.add(m); } map.put(aggList.get(level -1 ).getField(), JSON.toJSONString(list)); result.add(map); return result; } } public BoolQueryBuilder getQueryBuilder(List<EsQueryParam> params) { BoolQueryBuilder db = null; if (params != null) { db = QueryBuilders.boolQuery(); for (EsQueryParam param : params) { if(param.getLogicOperator() == LogicOperator.AND && param.getOperator() == Operator.EQUAL) { db = db.must(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if(param.getLogicOperator() == LogicOperator.AND && param.getOperator() == Operator.LIKE) { db = db.must(QueryBuilders.wildcardQuery(param.getField(), param.getValue())); } else if(param.getLogicOperator() == LogicOperator.OR && param.getOperator() == Operator.LIKE) { db = db.should(QueryBuilders.wildcardQuery(param.getField(), param.getValue())); } else if(param.getLogicOperator() == LogicOperator.MUST_NOT && param.getOperator() == Operator.LIKE) { db = db.mustNot(QueryBuilders.wildcardQuery(param.getField(), param.getValue())); } else if(param.getLogicOperator() == LogicOperator.MUST_NOT && param.getOperator() == Operator.EQUAL) { db = db.mustNot(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if(param.getOperator() == Operator.GT) { db = db.must(QueryBuilders.rangeQuery(param.getField()).gt(param.getValue())); } else if(param.getOperator() == Operator.GTE) { db = db.must(QueryBuilders.rangeQuery(param.getField()).gte(param.getValue())); } else if(param.getOperator() == Operator.LT) { db = db.must(QueryBuilders.rangeQuery(param.getField()).lt(param.getValue())); } else if(param.getOperator() == Operator.LTE) { db = db.must(QueryBuilders.rangeQuery(param.getField()).lte(param.getValue())); } else if (param.getLogicOperator() == LogicOperator.OR) { db = db.should(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if (param.getLogicOperator() == LogicOperator.AND ) { db = db.must(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if (param.getOperator() == Operator.EQUAL ) { db = db.must(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if (param.getOperator() == Operator.NOTEQUAL ) { db = db.mustNot(QueryBuilders.matchQuery(param.getField(), param.getValue())); } else if(param.getOperator() == Operator.TERMS) { db = db.must(QueryBuilders.termsQuery(param.getField(), param.getTermsList()).minimumMatch(1)); } else if (param.getLogicOperator() == null &¶m.getOperator() == null ) { db = db.must(QueryBuilders.matchQuery(param.getField(), param.getValue())); } } } return db; } @Override public boolean createType(Client client, String index, String type, String mapping) { // TODO Auto-generated method stub IndicesExistsRequest indexrequest = new IndicesExistsRequest(index); boolean exist = client.admin().indices().exists(indexrequest).actionGet().isExists(); if (! exist) { client.admin().indices().create(new CreateIndexRequest(index)).actionGet(); } PutMappingRequest putMappingRequest = new PutMappingRequest(index); putMappingRequest.type(type); putMappingRequest.source(mapping); PutMappingResponse putMappingResponse = client.admin().indices().putMapping(putMappingRequest).actionGet(); return putMappingResponse.isAcknowledged(); } @Override public boolean isIndexExistsByFieldVal(Client client, String index, String type, String field, String fieldVal) { // TODO Auto-generated method stub SearchRequestBuilder searchRequest = null ; boolean result = false; try { searchRequest = client.prepareSearch(index).setTypes(type).setQuery(QueryBuilders.matchQuery(field, fieldVal)); SearchResponse response = searchRequest.execute().actionGet(); result = (response.getHits().hits().length > 0) ? true : false; } catch (Exception e ) { e.printStackTrace(); return false; } return result; } @Override public SearchHits termsQuery(Client client, String index, String type,String field,List<String> terms) { SearchRequestBuilder searchRequest = null ; QueryBuilder qb = QueryBuilders.termsQuery(field, terms).minimumMatch(1); searchRequest = client.prepareSearch(index).setTypes(type).setQuery(qb).setSize(1000000000); SearchResponse response = searchRequest.execute().actionGet(); return response.getHits(); //后续优化 } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!
相关推荐
Elasticsearch查询客户端是用于与ES服务器通信的软件,它们提供了多种语言的API,允许开发者以编程方式执行索引、搜索、更新和删除等操作。常见的Elasticsearch客户端包括: - **Jest**:一个轻量级的Java REST...
描述中提到的步骤是下载Elasticsearch后进行解压,然后根据需求选择合适版本的Elasticsearch进行操作。解压后,进入`bin`目录启动Elasticsearch服务,这通常是通过运行`elasticsearch.bat`(Windows)或`./elastic...
在IT行业中,PHP和Elasticsearch的结合使用是常见的数据处理和搜索引擎构建方案。这篇文本将深入探讨如何在PHP环境中操作Elasticsearch,以及在ThinkPHP框架中集成这两个技术。 首先,Elasticsearch是一个分布式、...
根据提供的文件信息,我们可以推断出本篇文章将围绕Elasticsearch 6.2.2版本进行详细介绍,包括其下载方式、主要功能特性以及在实际应用中的常见用途。 ### Elasticsearch简介 Elasticsearch是一款基于Lucene的...
可通过 Kibana 可以很方便地对 Elasticsearch 进行数据操作。Kibana 可以实现数据可视化,它的作用是在 Elasticsearch 中对数据进行管理和展示。它能够通过图表的形式把数据呈现给用户。Kibana 可以提供各种可视化的...
Elasticsearch提供多种查询方式,其中Term查询和Match查询是两种常见的文本匹配方式: - Term查询:这种查询方式是精确匹配,会忽略掉分析过程,直接查找原始的关键词。如果搜索的词与索引中的完全相同,那么才会...
标签《ES Java API 中文文档》强调了文档的内容属性,它属于ElasticSearch的一个重要组成部分,即用Java语言进行数据交互和操作的应用程序接口部分。 从部分内容中可以提取出以下知识点: 1. **Transport Client**...
Elasticsearch 常见的应用场景包括: - **日志分析**:收集、存储、分析大量系统日志,发现异常和趋势。 - **网站搜索**:提供网站内容的快速、精准搜索体验。 - **业务数据分析**:实时分析业务数据,支持业务决策...
SpringBoot整合Elasticsearch是现代Java开发中常见的一项任务,因为SpringBoot的便捷性和Elasticsearch的高效搜索能力,使得这种结合在数据检索、分析和日志存储等领域广泛应用。本项目"springboot-elasticsearch-...
Elasticsearch工具类是开发中常见的一种抽象封装,旨在简化与Elasticsearch数据库的交互,提高代码的可读性和可维护性。Elasticsearch是一种基于Lucene的分布式、RESTful搜索和分析引擎,广泛用于实时大数据分析和...
4. **REST请求模拟**:提供一个交互式的HTTP请求构建器,支持GET、POST、PUT、DELETE等常见HTTP方法,可以方便地测试和调试Elasticsearch API。 5. **映射查看与编辑**:查看和修改索引的映射设置,理解字段的数据...
Python操作ElasticSearch是将Python编程语言与Elasticsearch(简称ES)数据库相结合,实现对数据的高效管理和分析。Elasticsearch是一个分布式、RESTful风格的搜索和数据分析引擎,广泛应用于日志分析、信息检索、...
在使用Spring Data Elasticsearch框架时,可能会遇到一个常见的问题,即版本兼容性问题。Spring Data Elasticsearch 5.4.0设计时可能并未考虑到与Elasticsearch 5.4.1的完全兼容,导致在升级Elasticsearch到5.4.1后...
在这个基于Elasticsearch 2.1.1的Java API基本操作代码示例中,我们将探讨如何利用Java API进行常见的数据操作,如索引创建、文档插入、查询以及更新。 首先,为了使用Elasticsearch的Java API,我们需要在项目中...
Elasticsearch提供了Java REST客户端,允许开发者直接通过Java代码与ES集群进行交互。这个工具类可能包含了如索引文档、查询、更新和删除文档等基本操作的封装,以及聚合、脚本等高级功能。例如,`IndexRequest`用于...
在Spring Boot应用中集成Elasticsearch是一项常见的任务,它能够帮助我们构建高性能的搜索和数据分析功能。Elasticsearch是一款开源的、分布式、实时的搜索与分析引擎,它被广泛用于日志分析、全文检索以及复杂的...
PHP作为后端开发的主流语言之一,与Elasticsearch的集成是常见的需求。在PHP中,通过Elasticsearch的PHP客户端库,我们可以轻松地进行索引创建、文档增删改查以及复杂的数据分析操作。 本文将详细介绍如何在PHP中...
为了简化对ES的操作,开发者们设计了各种框架,其中"easy-ES"就是一个旨在使Elasticsearch操作更简单易用的框架。本文将详细介绍如何使用easy-ES来轻松地进行Elasticsearch的数据操作和查询。 ### 1. easy-ES框架...
常见的 Elasticsearch 性能测试工具有以下几种: 1. **JMeter**:一个开源的 Java 应用,可以创建复杂的测试计划,包括搜索、索引和数据获取操作。 2. **Bigdesk**:Elasticsearch 自带的监控工具,提供实时性能...