org.elasticsearch.search.aggregations.Aggregation Java Examples

The following examples show how to use org.elasticsearch.search.aggregations.Aggregation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlogRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 8 votes vote down vote up
public List<Comment> getCommentsForStatus(String status,int from, int size) {
	
   IncludeExclude includeExclude = new IncludeExclude(status, null);
	
   NestedAggregationBuilder aggregation = AggregationBuilders.nested("aggChild", "comments").
								  subAggregation(AggregationBuilders.terms("aggStatsComment").
								  field("comments.status").
								  includeExclude(includeExclude).
								  subAggregation(AggregationBuilders.topHits("aggSortComment").size(10).sort("comments.createdDate", SortOrder.DESC))
	);

	SearchResponse response = elasticsearchTemplate.getClient().prepareSearch("blog")
	  .setTypes("blog")
	  .addAggregation(aggregation)
	  .execute().actionGet();
	
	List<Aggregation> responseAgg = response.getAggregations().asList();
	
	return getAllCommentsWithStatusFromJson(responseAgg.get(0).toString());
	
}
 
Example #2
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 6 votes vote down vote up
public TResult reduce(ElasticsearchSearchQueryBase query, Map<Object, List<MultiBucketsAggregation.Bucket>> bucketsByKey) {
    List<TBucket> buckets = new ArrayList<>();
    for (Map.Entry<Object, List<MultiBucketsAggregation.Bucket>> bucketsByKeyEntry : bucketsByKey.entrySet()) {
        String key = bucketKeyToString(bucketsByKeyEntry.getKey(), null);
        long count = 0;
        List<Aggregation> subAggs = new ArrayList<>();
        for (MultiBucketsAggregation.Bucket b : bucketsByKeyEntry.getValue()) {
            count += b.getDocCount();
            for (Aggregation subAgg : b.getAggregations()) {
                subAggs.add(subAgg);
            }
        }
        Map<String, AggregationResult> nestedResults = reduceAggregationResults(query, getAggregationResultsByName(query, subAggs));
        buckets.add(createBucket(key, count, nestedResults, bucketsByKeyEntry.getValue()));
    }
    return bucketsToResults(buckets);
}
 
Example #3
Source File: AggregationResponseHandle.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private static <A extends Aggregation> void route(Bucket bucket, A a) {
    if (a instanceof Terms) {
        bucket.setBuckets(terms(a));
    } else if (a instanceof Range) {
        bucket.setBuckets(range(a));
    } else if (a instanceof Histogram) {
        bucket.setBuckets(range(a));
    } else if (a instanceof Avg) {
        bucket.setAvg(avg(a));
    } else if (a instanceof Min) {
        bucket.setMin(min(a));
    } else if (a instanceof Max) {
        bucket.setMax(max(a));
    } else if (a instanceof Sum) {
        bucket.setSum(sum(a));
    } else if (a instanceof Stats) {
        stats(bucket, a);
    }  else if (a instanceof ValueCount) {
        bucket.setValueCount(count(a));
    } else {
        throw new UnsupportedOperationException("不支持的聚合类型");
    }
}
 
Example #4
Source File: ESQueryResponseHandler.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 获取聚合结果,进行统一封装 //@param functionNames 检索提供的函数别名 //@param innerAggregations
 * es 聚合底层聚合结果
 *
 * @param key         分组组合key
 * @param countCesult 统一统计结果
 */
private void wrapCountResult(Aggregation agregation, String key, Map<String, List<Map<String, Object>>> countCesult) {

    if (agregation instanceof NumericMetricsAggregation.SingleValue) {// max
        // ,min,sum
        final NumericMetricsAggregation.SingleValue numericProperty = (NumericMetricsAggregation.SingleValue) agregation;

        final String functionName = numericProperty.getName();
        final double value = numericProperty.value();

        final HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put(key, value);

        List<Map<String, Object>> groupList = countCesult.get(functionName);
        if (groupList == null) {
            groupList = new ArrayList<>();
        }
        groupList.add(stringObjectHashMap);

        countCesult.put(functionName, groupList);
    }
}
 
Example #5
Source File: ESStatisticResponseHandler.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public Map<String, Number> handler(final Aggregations aggregations) {
    Map<String, Number> statisticResult = new HashMap<>();
    if (aggregations == null) {
        return null;
    }

    for (Aggregation aggregation : aggregations.asList()) {
        if (aggregation instanceof NumericMetricsAggregation.SingleValue) {
            final NumericMetricsAggregation.SingleValue numericProperty = (NumericMetricsAggregation
                    .SingleValue) aggregation;
            final String functionName = numericProperty.getName();
            final double value = numericProperty.value();

            statisticResult.put(functionName, value);
        }
    }
    return statisticResult;
}
 
Example #6
Source File: SearchService.java    From leyou with Apache License 2.0 6 votes vote down vote up
/**
 * 解析品牌聚合结果
 *
 * @param aggregation
 * @return
 */
private List<Brand> getBrandAggResult(Aggregation aggregation) {
    try {
        // 处理聚合结果集
        LongTerms brandAgg = (LongTerms) aggregation;
        List<Long> bids = new ArrayList<>();
        for (LongTerms.Bucket bucket : brandAgg.getBuckets()) {
            bids.add(bucket.getKeyAsNumber().longValue());
        }
        // 根据id查询品牌
        return this.brandClient.queryBrandByIds(bids);
    } catch (Exception e) {
        logger.error("品牌聚合出现异常:", e);
        return null;
    }
}
 
Example #7
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 6 votes vote down vote up
private static StatisticsResult reduceStatisticsResults(List<Aggregation> aggs) {
    List<StatisticsResult> results = new ArrayList<>();
    for (Aggregation agg : aggs) {
        if (agg instanceof ExtendedStats) {
            ExtendedStats extendedStats = (ExtendedStats) agg;
            long count = extendedStats.getCount();
            double sum = extendedStats.getSum();
            double min = extendedStats.getMin();
            double max = extendedStats.getMax();
            double standardDeviation = extendedStats.getStdDeviation();
            results.add(new StatisticsResult(count, sum, min, max, standardDeviation));
        } else {
            throw new VertexiumException("Aggregation is not a statistics: " + agg.getClass().getName());
        }
    }
    return StatisticsResult.combine(results);
}
 
Example #8
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 6 votes vote down vote up
public TResult reduce(ElasticsearchSearchQueryBase query, Map<Object, List<MultiBucketsAggregation.Bucket>> bucketsByKey) {
    List<TBucket> buckets = new ArrayList<>();
    for (Map.Entry<Object, List<MultiBucketsAggregation.Bucket>> bucketsByKeyEntry : bucketsByKey.entrySet()) {
        String key = bucketKeyToString(bucketsByKeyEntry.getKey(), null);
        long count = 0;
        List<Aggregation> subAggs = new ArrayList<>();
        for (MultiBucketsAggregation.Bucket b : bucketsByKeyEntry.getValue()) {
            count += b.getDocCount();
            for (Aggregation subAgg : b.getAggregations()) {
                subAggs.add(subAgg);
            }
        }
        Map<String, AggregationResult> nestedResults = reduceAggregationResults(query, getAggregationResultsByName(query, subAggs));
        buckets.add(createBucket(key, count, nestedResults, bucketsByKeyEntry.getValue()));
    }
    return bucketsToResults(buckets);
}
 
Example #9
Source File: SearchFeatureDaoTests.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
@Test
public void getFeaturesForPeriod_returnNonEmpty_givenDefaultValue() throws Exception {
    long start = 100L;
    long end = 200L;

    // pre-conditions
    when(ParseUtils.generateInternalFeatureQuery(eq(detector), eq(start), eq(end), eq(xContent))).thenReturn(searchSourceBuilder);
    when(searchResponse.getHits()).thenReturn(new SearchHits(new SearchHit[0], new TotalHits(0L, TotalHits.Relation.EQUAL_TO), 1f));

    List<Aggregation> aggList = new ArrayList<>(1);

    NumericMetricsAggregation.SingleValue agg = mock(NumericMetricsAggregation.SingleValue.class);
    when(agg.getName()).thenReturn("deny_max");
    when(agg.value()).thenReturn(0d);

    aggList.add(agg);

    Aggregations aggregations = new Aggregations(aggList);
    when(searchResponse.getAggregations()).thenReturn(aggregations);

    // test
    Optional<double[]> result = searchFeatureDao.getFeaturesForPeriod(detector, start, end);

    // verify
    assertTrue(result.isPresent());
}
 
Example #10
Source File: JdbcResponseExtractor.java    From elasticsearch-sql with MIT License 6 votes vote down vote up
private void parseAggregations(Aggregations aggregations, Map<String, Object> aggMap, String parent) {
    for (Aggregation aggregation : aggregations) {
        if (aggregation instanceof ParsedNested) {
            parseNestedAggregation(aggregation, aggMap);
        } else if (aggregation instanceof ParsedComposite) {
            parseCompositeAggregation(aggregation, aggMap, parent);
        } else if (aggregation instanceof ParsedTerms) {
            parseTermsAggregation(aggregation, aggMap, parent);
        } else if (aggregation instanceof ParsedTopHits) {
            parseTopHitsAggregation(aggregation, aggMap);
        } else if (aggregation instanceof ParsedCardinality) {
            parseCardinalityAggregation(aggregation, aggMap);
        } else if (aggregation instanceof ParsedRange) {
            parseRangeAggregation(aggregation, aggMap);
        } else if (aggregation instanceof ParsedGeoBounds) {
            parseGeoBoundAggregation(aggregation, aggMap);
        }
    }
}
 
Example #11
Source File: EsSearchResponse.java    From mall with Apache License 2.0 6 votes vote down vote up
/**
 * 获得属性的聚合
 *
 * @param aggregation 属性的聚合
 * @return 返回属性的聚合
 */
private static Map<String, List<String>> getAttributes(Aggregation aggregation) {
    Map<String, List<String>> attributes = new HashMap<>();

    if (Objects.isNull(aggregation)) {
        return attributes;
    }

    InternalNested nested = (InternalNested) aggregation;
    if (CollectionUtils.isEmpty(nested.getAggregations().asList())) {
        return attributes;
    }
    StringTerms stringTerms = (StringTerms) nested.getAggregations().asList().get(0);
    stringTerms.getBuckets().stream().forEach(bucket -> attributes.put((String) bucket.getKey(), getStringTerms(bucket.getAggregations().asList().get(0))));
    return attributes;
}
 
Example #12
Source File: SearchAggregationParser.java    From sql4es with Apache License 2.0 6 votes vote down vote up
/**
 * Parse an aggregation performed without grouping.
 * @param filter
 * @param rs
 * @throws SQLException
 */
private void processFilterAgg(InternalFilter filter, ESResultSet rs) throws SQLException{
	//String name = global.getName(); // we do not care about the global name for now
	List<Object> row = rs.getNewRow();
	Column count = null;
	for(Column c : rs.getHeading().columns())
		if(c.getOp() == Operation.COUNT) count = c;
	
	if(count != null){
		row.set(count.getIndex(), filter.getDocCount());
	}
	for(Aggregation agg : filter.getAggregations()){
		if(agg instanceof InternalNumericMetricsAggregation.SingleValue){
			InternalNumericMetricsAggregation.SingleValue numericAgg = 
					(InternalNumericMetricsAggregation.SingleValue)agg;
			String name =numericAgg.getName();
			Column column = rs.getHeading().getColumnByLabel(name);
			if(column == null){
				throw new SQLException("Unable to identify column for "+name);
			}
			row.set(column.getIndex(), numericAgg.value());
		}else throw new SQLException("Unable to parse aggregation of type "+agg.getClass());
	}
	rs.add(row);
}
 
Example #13
Source File: ResultUtils.java    From vind with Apache License 2.0 6 votes vote down vote up
private static Pair<FieldDescriptor<?> ,TermFacetResult<?>> getTermFacetResults(Aggregation aggregation, Facet.TermFacet termFacet, DocumentFactory factory) {
    final TermFacetResult<?> result = new TermFacetResult<>();
    final FieldDescriptor<?> field = factory.getField(termFacet.getFieldName());
    Optional.ofNullable(aggregation)
            .ifPresent(agg ->
                    ((ParsedTerms) aggregation).getBuckets().stream()
                        .map( bucket -> {
                            final Object key = Number.class.isAssignableFrom(field.getType()) ?  bucket.getKeyAsNumber() : bucket.getKeyAsString();
                            return Pair.of(key, bucket.getDocCount());
                        })
                        .map( p -> new FacetValue(
                                DocumentUtil.castForDescriptor(p.getKey(), field, FieldUtil.Fieldname.UseCase.Facet), p.getValue()))
                        .forEach(result::addFacetValue));

    return Pair.of(termFacet.getFieldDescriptor(), result);
}
 
Example #14
Source File: FactSearchManager.java    From act-platform with ISC License 6 votes vote down vote up
private Aggregation resolveChildAggregation(Aggregations aggregations, String targetAggregationName) {
  if (aggregations == null) return null;

  for (Aggregation aggregation : aggregations) {
    // Check if 'aggregation' is already the target aggregation.
    if (aggregation.getName().equals(targetAggregationName)) {
      return aggregation;
    }

    // Otherwise check all sub aggregations if applicable.
    if (HasAggregations.class.isAssignableFrom(aggregation.getClass())) {
      Aggregation target = resolveChildAggregation(HasAggregations.class.cast(aggregation).getAggregations(), targetAggregationName);
      if (target != null) return target;
    }
  }

  // Couldn't find target aggregation.
  return null;
}
 
Example #15
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static CardinalityResult reduceCardinalityResults(ElasticsearchSearchQueryBase query, List<Aggregation> aggs) {
    if (aggs.size() == 0) {
        return new CardinalityResult(0);
    }
    if (aggs.size() == 1) {
        Aggregation agg = aggs.get(0);
        if (agg instanceof InternalCardinality) {
            return new CardinalityResult(((InternalCardinality) agg).getValue());
        } else {
            throw new VertexiumException("Unhandled aggregation result type: " + agg.getClass().getName());
        }
    }
    throw new VertexiumException("Cannot reduce multiple " + CardinalityAggregation.class + "(count: " + aggs.size() + ")");
}
 
Example #16
Source File: CSVResultsExtractor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private  boolean allNumericAggregations(Aggregations aggregations) {
    List<Aggregation> aggregationList = aggregations.asList();
    for(Aggregation aggregation : aggregationList){
        if(!(aggregation instanceof NumericMetricsAggregation)){
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: DistributedTableMetadataManager.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private void evaluateDoubleEstimation(Aggregation value, String table, String key, FieldType type,
                                      Map<String, EstimationData> estimationDataMap, long hits) {
    if(value instanceof Percentiles) {
        Percentiles percentiles = (Percentiles)value;
        double[] values = new double[10];
        for(int i = 10; i <= 100; i += 10) {
            final Double percentile = percentiles.percentile(i);
            values[(i / 10) - 1] = percentile.isNaN() ? 0 : percentile;
        }
        logger.info("table:{} field:{} type:{} aggregationType:{} value:{}", table, key, type,
                "percentile", values
        );
        estimationDataMap.put(key, PercentileEstimationData.builder()
                .values(values)
                .count(hits)
                .build());
    } else if(value instanceof Cardinality) {
        Cardinality cardinality = (Cardinality) value;
        logger.info("table:{} field:{} type:{} aggregationType:{} value:{}", table, key, type,
                CARDINALITY, cardinality.getValue()
        );
        EstimationData estimationData = estimationDataMap.get(key.replace("_", ""));
        if (estimationData instanceof PercentileEstimationData) {
            ((PercentileEstimationData) estimationData).setCardinality(cardinality.getValue());
        } else {
            estimationDataMap.put(key.replace("_", ""), PercentileEstimationData.builder()
                    .cardinality(cardinality.getValue())
                    .build());
        }
    }
}
 
Example #18
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static Map<String, AggregationResult> reduceAggregationResults(ElasticsearchSearchQueryBase query, Map<String, List<Aggregation>> aggsByName) {
    Map<String, AggregationResult> results = new HashMap<>();
    for (Map.Entry<String, List<Aggregation>> entry : aggsByName.entrySet()) {
        results.put(entry.getKey(), reduceAggregationResults(query, query.getAggregationByName(entry.getKey()), entry.getValue()));
    }
    return results;
}
 
Example #19
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static Map<String, List<Aggregation>> getAggregationResultsByName(ElasticsearchSearchQueryBase query, Iterable<Aggregation> aggs) {
    Map<String, List<Aggregation>> aggsByName = new HashMap<>();
    if (aggs == null) {
        return aggsByName;
    }
    for (Aggregation agg : aggs) {
        if (agg.getName().equals(ElasticsearchSearchQueryBase.TOP_HITS_AGGREGATION_NAME)) {
            continue;
        }
        String aggName = query.getAggregationName(agg.getName());
        List<Aggregation> l = aggsByName.computeIfAbsent(aggName, k -> new ArrayList<>());
        l.add(agg);
    }
    return aggsByName;
}
 
Example #20
Source File: SearchResult.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
/**
 * 讲es的field域转换为你Object
 * 
 * @param fields
 * @return
 * @throws SqlParseException
 */
private Map<String, Object> toAggsMap(Map<String, Aggregation> fields) throws SqlParseException {
	Map<String, Object> result = new HashMap<>();
	for (Entry<String, Aggregation> entry : fields.entrySet()) {
		result.put(entry.getKey(), covenValue(entry.getValue()));
	}
	return result;
}
 
Example #21
Source File: TransportBasedClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private void setAggregations(Aggregations aggregations, ActionResponse actionResp) {
  // Only the result of the first aggregation is returned
  //
  final Aggregation agg = aggregations.asList().get(0);

  if (agg instanceof InternalMetricsAggregation) {
    actionResp.addAggregation(new AggWrapper(AggWrapper.AggregationType.SIMPLE,
        XContentHelper.toString((InternalMetricsAggregation) agg).toString()));
  } else if (agg instanceof InternalSingleBucketAggregation) {
    actionResp.addAggregation(new AggWrapper(AggWrapper.AggregationType.SIMPLE,
        XContentHelper.toString((InternalSingleBucketAggregation) agg).toString()));
  } else if (agg instanceof InternalMultiBucketAggregation) {
    final Set<String> headerKeys = new HashSet<>();
    final List<Map<String, Object>> buckets = new LinkedList<>();
    final InternalMultiBucketAggregation multiBucketAgg = (InternalMultiBucketAggregation) agg;

    for (final MultiBucketsAggregation.Bucket bucket : multiBucketAgg.getBuckets()) {
      try {
        final XContentBuilder builder = XContentFactory.jsonBuilder();
        bucket.toXContent(builder, null);
        actionResp.addAggregation(
            new AggWrapper(AggWrapper.AggregationType.MULTI_BUCKETS, builder.string()));
      } catch (final IOException e) {
        // Ignored
      }
    }
  }
}
 
Example #22
Source File: SearchAggregationParser.java    From sql4es with Apache License 2.0 5 votes vote down vote up
/**
 * Parses an ES aggregation into a set of ResultRows
 * @param agg
 * @return
 * @throws SQLException
 */
public void parseAggregation(Aggregation agg, ESResultSet rs) throws SQLException{
	if(agg instanceof Terms){
		dfsAggregations((Terms)agg, rs, rs.getNewRow());
	}else if (agg instanceof InternalFilter){
		processFilterAgg((InternalFilter)agg, rs);
	}else if (agg instanceof InternalCardinality){
		processCardinalityAgg((InternalCardinality)agg, rs);
	}else throw new SQLException ("Unknown aggregation type "+agg.getClass().getName());
}
 
Example #23
Source File: CustomSearchRepositoryImpl.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Long> aggregateByRawField(String field, String filtre) {

    TermsBuilder aggregation = AggregationBuilders.terms("top_" + field)
        .field(field + ".raw")
        .size(0)// le résultat n'est pas complet si on ne précise pas la taille, 0 : infini
        // (voir : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_size)
        .order(Terms.Order.aggregation("_count", false));

    SearchResponse response = createResponse(filtre, aggregation);

    Map<String, Aggregation> results = response.getAggregations().asMap();
    StringTerms topField = (StringTerms) results.get("top_" + field);

    //sur l'ensemble des buckets, triés par ordre décroissant sur le nombre de documents
    // on retourne une Map (LinkedHashMap) pour conserver l'ordre avec la clé, le nom du champ (exemple version), et la valeur, le nombre de docs
    //exemple :
    // "trunk" -> 34012
    // "branche_1" -> 35800
    return topField.getBuckets()
        .stream()
        .sorted(Comparator.comparing(Terms.Bucket::getDocCount).reversed())
        .collect(
            Collectors.toMap(bucket -> bucket.getKeyAsString(), bucket -> bucket.getDocCount(), (v1, v2) -> v1, LinkedHashMap::new
            ));

}
 
Example #24
Source File: DistributedTableMetadataManager.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private void handleFirstPhaseMultiSearchResponse(MultiSearchResponse multiResponse, String table, Map<String, FieldMetadata> fields,
                                                 Map<String, EstimationData> estimationDataMap) {
    for(MultiSearchResponse.Item item : multiResponse.getResponses()) {
        SearchResponse response = validateAndGetSearchResponse(item, table);
        if(null == response) {
            continue;
        }
        final long hits = response.getHits()
                .getTotalHits();
        Map<String, Aggregation> output = response.getAggregations().asMap();
        output.forEach((key, value) -> {
            FieldMetadata fieldMetadata = fields.get(key);
            if(fieldMetadata == null) {
                fieldMetadata = fields.get(key.replace("_", ""));
            }
            if(fieldMetadata == null) {
                return;
            }
            switch (fieldMetadata.getType()) {
                case STRING:
                    evaluateStringEstimation(value, table, key, fieldMetadata.getType(), estimationDataMap, hits);
                    break;
                case INTEGER:
                case LONG:
                case FLOAT:
                case DOUBLE:
                    evaluateDoubleEstimation(value, table, key, fieldMetadata.getType(), estimationDataMap, hits);
                    break;
                case BOOLEAN:
                    evaluateBooleanEstimation(key, estimationDataMap);
                break;
                case DATE:
                case OBJECT:
                case TEXT:
                case KEYWORD:
            }
        });
    }
}
 
Example #25
Source File: ResultUtils.java    From vind with Apache License 2.0 5 votes vote down vote up
private static Pair<String, IntervalFacetResult> getIntervalFacetResults(Aggregation aggregation, Facet.IntervalFacet intervalFacet) {
    final List<FacetValue<String>> values = new ArrayList<>();
    Optional.ofNullable(aggregation)
            .ifPresent(agg -> ((ParsedRange) agg).getBuckets().stream()
                    .map(bucket -> new FacetValue( bucket.getKey(), bucket.getDocCount()))
                    .forEach(values::add));

    final IntervalFacetResult intervalFacetResult = new IntervalFacetResult(values);

    return Pair.of(intervalFacet.getFacetName(), intervalFacetResult);
}
 
Example #26
Source File: ResultUtils.java    From vind with Apache License 2.0 5 votes vote down vote up
private static Pair<String ,RangeFacetResult<?>> getRangeFacetResults(Aggregation aggregation, Facet rangeFacet) {

            switch (rangeFacet.getType()) {
                case "NumericRangeFacet":
                    final Facet.NumericRangeFacet numericRangeFacet = (Facet.NumericRangeFacet) rangeFacet;

                    final List<FacetValue> numericValues =  new ArrayList<>();

                    Optional.ofNullable(aggregation)
                            .ifPresent(agg -> ((ParsedHistogram)((ParsedRange) agg).getBuckets().get(0).getAggregations().getAsMap().get(rangeFacet.getFacetName())).getBuckets().stream()
                                .map(rangeBucket -> new FacetValue(
                                        DocumentUtil.castForDescriptor(rangeBucket.getKey(), numericRangeFacet.getFieldDescriptor(), FieldUtil.Fieldname.UseCase.Facet),
                                        rangeBucket.getDocCount()))
                                .forEach(numericValues::add));
                    return Pair.of(
                            rangeFacet.getFacetName(),
                            new RangeFacetResult(numericValues,numericRangeFacet.getStart(), numericRangeFacet.getEnd(), numericRangeFacet.getGap().longValue()));
                default:
                    final Facet.DateRangeFacet dateRangeFacet = (Facet.DateRangeFacet) rangeFacet;

                    final List<FacetValue> dateValues =  new ArrayList<>();

                    Optional.ofNullable(aggregation)
                            .ifPresent(agg -> ((ParsedDateHistogram)((ParsedDateRange) agg).getBuckets().get(0).getAggregations().getAsMap().get(dateRangeFacet.getFacetName())).getBuckets().stream()
                                    .map(rangeBucket -> new FacetValue(
                                            DocumentUtil.castForDescriptor(rangeBucket.getKey(), dateRangeFacet.getFieldDescriptor(), FieldUtil.Fieldname.UseCase.Facet),
                                            rangeBucket.getDocCount()))
                                    .forEach(dateValues::add));
                    return Pair.of(
                            rangeFacet.getFacetName(),
                            new RangeFacetResult(dateValues,dateRangeFacet.getStart(), dateRangeFacet.getEnd(), dateRangeFacet.getGap().longValue()));
            }

    }
 
Example #27
Source File: SimpleSearchQueryBuilder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public <T, A extends Aggregation> T mapAggregation(String name, Function<A, T> mapper) {
	A aggr = getAggregation(name);
	if(aggr==null){
		return null;
	}
	return mapper.apply(aggr);
}
 
Example #28
Source File: ResultUtils.java    From vind with Apache License 2.0 5 votes vote down vote up
private static TermFacetResult<String> getTypeFacetResults(Aggregation aggregation) {
    final TermFacetResult<String> result = new TermFacetResult<>();
    Optional.ofNullable(aggregation)
            .ifPresent(agg ->
                    ((ParsedStringTerms) aggregation).getBuckets().stream()
                            .map( termBucket -> new FacetValue<>( termBucket.getKey().toString(), termBucket.getDocCount()))
                            .forEach(result::addFacetValue));
    return result;
}
 
Example #29
Source File: ResultUtils.java    From vind with Apache License 2.0 5 votes vote down vote up
private static Pair<String, QueryFacetResult<?>> getQueryFacetResults(Aggregation aggregation, Facet.QueryFacet queryFacet) {

        if(Objects.nonNull(aggregation)) {
            return Pair.of( queryFacet.getFacetName(),
                    new QueryFacetResult(queryFacet.getFilter(), new Long(((ParsedFilters) aggregation).getBucketByKey("0").getDocCount()).intValue()));
       }

        return Pair.of( queryFacet.getFacetName(),
                new QueryFacetResult<>(queryFacet.getFilter(),0));
    }
 
Example #30
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static Map<String, List<Aggregation>> getAggregationResultsByName(ElasticsearchSearchQueryBase query, Iterable<Aggregation> aggs) {
    Map<String, List<Aggregation>> aggsByName = new HashMap<>();
    if (aggs == null) {
        return aggsByName;
    }
    for (Aggregation agg : aggs) {
        if (agg.getName().equals(ElasticsearchSearchQueryBase.TOP_HITS_AGGREGATION_NAME)) {
            continue;
        }
        String aggName = query.getAggregationName(agg.getName());
        List<Aggregation> l = aggsByName.computeIfAbsent(aggName, k -> new ArrayList<>());
        l.add(agg);
    }
    return aggsByName;
}