org.elasticsearch.search.aggregations.metrics.tophits.TopHits Java Examples

The following examples show how to use org.elasticsearch.search.aggregations.metrics.tophits.TopHits. 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: UKAggTopResultExtractor.java    From youkefu with Apache License 2.0 7 votes vote down vote up
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
	Aggregations aggregations = response.getAggregations();
	Terms agg = aggregations.get(term) ;
	long total = agg.getSumOfOtherDocCounts() ;
	List<T> results = new ArrayList<T>();
	if(agg.getBuckets()!=null && agg.getBuckets().size()>0){
		for (int i = pageable.getPageNumber()*pageable.getPageSize();i<agg.getBuckets().size()  ; i++) {
			Terms.Bucket entry = agg.getBuckets().get(i) ;
			if(!StringUtils.isBlank(name) && entry.getAggregations().get(name)!=null){
				TopHits topHits = entry.getAggregations().get(name);
				for (SearchHit hit : topHits.getHits().getHits()) {
					T data = mapEntity(hit.getSourceAsString() , hit , clazz) ;
					if(data instanceof UKAgg){
						((UKAgg) data).setRowcount((int) topHits.getHits().getTotalHits());
					}
					results.add(data) ;
				}
			}
		}
	}
	return new AggregatedPageImpl<T>(results, pageable, total);
}
 
Example #2
Source File: FactSearchManager.java    From act-platform with ISC License 5 votes vote down vote up
private List<ObjectDocument> retrieveSearchObjectsResultValues(SearchResponse response) {
  List<ObjectDocument> result = ListUtils.list();

  Aggregation uniqueObjectsAggregation = resolveChildAggregation(response.getAggregations(), UNIQUE_OBJECTS_AGGREGATION_NAME);
  if (!(uniqueObjectsAggregation instanceof Terms)) {
    LOGGER.warning("Could not retrieve result values when searching for Objects.");
    return result;
  }

  List<? extends Terms.Bucket> buckets = Terms.class.cast(uniqueObjectsAggregation).getBuckets();
  if (CollectionUtils.isEmpty(buckets)) {
    // No buckets means no results.
    return result;
  }

  // Each bucket contains one unique Object, where the TopHits aggregation provides the document source.
  for (Terms.Bucket bucket : buckets) {
    Aggregation uniqueObjectsSourceAggregation = bucket.getAggregations().get(UNIQUE_OBJECTS_SOURCE_AGGREGATION_NAME);
    if (!(uniqueObjectsSourceAggregation instanceof TopHits)) continue;

    // Each bucket should contain only one hit with one unique Object.
    SearchHits hits = TopHits.class.cast(uniqueObjectsSourceAggregation).getHits();
    if (hits.getHits().length < 1) continue;

    // Retrieve Object document from provided search hit.
    ObjectDocument document = decodeObjectDocument(toBytes(hits.getAt(0).getSourceRef()));
    if (document != null) {
      result.add(document);
    }
  }

  return result;
}
 
Example #3
Source File: NpmSearchResponseFactory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Builds a search response containing each of the included search buckets.
 */
public NpmSearchResponse buildResponseForResults(final List<Terms.Bucket> buckets, final int size, final int from) {
  List<NpmSearchResponseObject> objects = buckets.stream()
      .map(bucket -> (TopHits) bucket.getAggregations().get("versions"))
      .map(TopHits::getHits)
      .map(searchHits -> searchHits.getAt(0))
      .map(this::buildSearchResponseObject)
      .skip(from)
      .limit(size)
      .collect(toList());

  return buildResponseForObjects(objects);
}
 
Example #4
Source File: NpmSearchResponseFactoryTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private List<Terms.Bucket> generateBuckets(final int count,
                                           final boolean includeAuthorName,
                                           final boolean includeAuthorEmail)
{
  List<Bucket> buckets = new ArrayList<>();
  for (int index = 0; index < count; index++) {
    Terms.Bucket bucket = mock(Terms.Bucket.class);
    Aggregations aggregations = mock(Aggregations.class);
    TopHits topHits = mock(TopHits.class);
    SearchHits searchHits = mock(SearchHits.class);
    SearchHit searchHit = mock(SearchHit.class);

    when(bucket.getAggregations()).thenReturn(aggregations);
    when(aggregations.get("versions")).thenReturn(topHits);
    when(topHits.getHits()).thenReturn(searchHits);
    when(searchHits.getAt(0)).thenReturn(searchHit);
    when(searchHit.getScore()).thenReturn(1.0F);

    if (includeAuthorEmail) {
      when(npmSearchHitExtractor.extractAuthorEmail(searchHit)).thenReturn("author-email-" + index);
    }
    if (includeAuthorName) {
      when(npmSearchHitExtractor.extractAuthorName(searchHit)).thenReturn("author-name-" + index);
    }
    when(npmSearchHitExtractor.extractBugsUrl(searchHit)).thenReturn("bugs-url-" + index);
    when(npmSearchHitExtractor.extractDescription(searchHit)).thenReturn("description-" + index);
    when(npmSearchHitExtractor.extractHomepage(searchHit)).thenReturn("homepage-url-" + index);
    when(npmSearchHitExtractor.extractRepositoryUrl(searchHit)).thenReturn("repository-url-" + index);
    when(npmSearchHitExtractor.extractKeywords(searchHit)).thenReturn(singletonList("keyword-" + index));
    when(npmSearchHitExtractor.extractLastModified(searchHit)).thenReturn(DateTime.now());
    when(npmSearchHitExtractor.extractName(searchHit)).thenReturn("name-" + index);
    when(npmSearchHitExtractor.extractVersion(searchHit)).thenReturn("version-" + index);

    buckets.add(bucket);
  }
  return buckets;
}
 
Example #5
Source File: ElasticsearchGraphQueryIterable.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private static String bucketKeyToString(Object bucketKey, TopHits exactMatchTopHits) {
    // to maintain backwards compatibility decimals ending in ".0" should not contain the decimal place
    if (bucketKey instanceof Number) {
        String strBucketKey = bucketKey.toString();
        if (strBucketKey.endsWith(".0")) {
            strBucketKey = strBucketKey.substring(0, strBucketKey.length() - 2);
        }
        return strBucketKey;
    }

    if (exactMatchTopHits != null) {
        if (exactMatchTopHits.getHits().getTotalHits() > 0) {
            SearchHit hit = exactMatchTopHits.getHits().getAt(0);
            for (Object o : hit.getSourceAsMap().values()) {
                // for multi-value properties find the item that matches regardless of case
                if (o instanceof Iterable) {
                    for (Object oItem : ((Iterable) o)) {
                        String oItemString = oItem.toString();
                        if (bucketKey.equals(oItemString.toLowerCase())) {
                            return oItemString;
                        }
                    }
                }

                return o.toString();
            }
        }
    }

    if (bucketKey instanceof org.elasticsearch.common.geo.GeoPoint) {
        String geohash = ((org.elasticsearch.common.geo.GeoPoint) bucketKey).getGeohash();
        return geohash.replaceAll("0+$", "");
    }
    return bucketKey.toString();
}