Example usage for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults

List of usage examples for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults.

Prototype

public List<T> getMappedResults() 

Source Link

Document

Returns the aggregation results.

Usage

From source file:com.epam.ta.reportportal.database.dao.LaunchRepositoryCustomImpl.java

@Cacheable(value = { CacheConfiguration.PROJECT_INFO_CACHE })
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from   ww  w.  ja v  a 2 s.c  om*/
public Map<String, Integer> findGroupedLaunchesByOwner(String projectName, String mode, Date from) {
    Map<String, Integer> output = new HashMap<>();
    Aggregation aggregation = newAggregation(match(where(PROJECT_ID_REFERENCE).is(projectName)),
            match(where(MODE).is(mode)), match(where(STATUS).ne(IN_PROGRESS.name())),
            match(where(START_TIME).gt(from)), group("$userRef").count().as("count"));

    AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Launch.class, Map.class);
    for (Map<String, String> entry : result.getMappedResults()) {
        String username = entry.get("_id");
        String count = String.valueOf(entry.get("count"));
        output.put(username, Integer.valueOf(count));
    }
    return output;
}

From source file:com.handu.open.dubbo.monitor.DubboMonitorService.java

/**
 * ??//w w w .  j  a  va 2s  . c o  m
 *
 * @param dubboInvoke
 * @return
 */
public List<DubboInvoke> countDubboInvokeInfo(DubboInvoke dubboInvoke) {
    if (StringUtils.isEmpty(dubboInvoke.getService()) || StringUtils.isEmpty(dubboInvoke.getMethod())
            || StringUtils.isEmpty(dubboInvoke.getType())) {
        logger.error("???");
        throw new RuntimeException("???");
    }
    TypedAggregation<DubboInvoke> aggregation = Aggregation.newAggregation(DubboInvoke.class,
            Aggregation.match(Criteria.where("service").is(dubboInvoke.getService()).and("method")
                    .is(dubboInvoke.getMethod()).and("type").is(dubboInvoke.getType()).and("invokeDate")
                    .gte(dubboInvoke.getInvokeDateFrom()).lte(dubboInvoke.getInvokeDateTo())),
            Aggregation.group("service", "method").sum("success").as("success").sum("failure").as("failure")
                    .sum("elapsed").as("elapsed").max("maxElapsed").as("maxElapsed").min("maxConcurrent")
                    .as("maxConcurrent"));
    AggregationResults<DubboInvoke> result = mongoTemplate.aggregate(aggregation, "dubboInvoke",
            DubboInvoke.class);

    return result.getMappedResults();
}

From source file:com.handu.open.dubbo.monitor.DubboMonitorService.java

/**
 * ?/*from w w w  .java 2  s .co  m*/
 *
 * @param dubboInvoke
 */
public List<DubboInvoke> countDubboInvoke(DubboInvoke dubboInvoke) {
    if (StringUtils.isEmpty(dubboInvoke.getService())) {
        logger.error("???");
        throw new RuntimeException("???");
    }

    TypedAggregation<DubboInvoke> aggregation = Aggregation.newAggregation(DubboInvoke.class,
            Aggregation.match(Criteria.where("service").is(dubboInvoke.getService()).and("method")
                    .is(dubboInvoke.getMethod()).and("type").is(dubboInvoke.getType()).and("invokeDate")
                    .gte(dubboInvoke.getInvokeDateFrom()).lte(dubboInvoke.getInvokeDateTo())),
            Aggregation
                    .project("service", "method", "type", "success", "failure", "elapsed", "maxElapsed",
                            "maxConcurrent", "invokeTime")
                    .andExpression("(invokeTime / " + dubboInvoke.getTimeParticle() + ") * "
                            + dubboInvoke.getTimeParticle())
                    .as("invokeTime"),
            Aggregation.group("service", "method", "type", "invokeTime").sum("success").as("success")
                    .sum("failure").as("failure").sum("elapsed").as("elapsed").max("maxElapsed")
                    .as("maxElapsed").min("maxConcurrent").as("maxConcurrent"),
            Aggregation.sort(Sort.Direction.ASC, "invokeTime"));
    AggregationResults<DubboInvoke> result = mongoTemplate.aggregate(aggregation, "dubboInvoke",
            DubboInvoke.class);
    return result.getMappedResults();
}

From source file:org.ingini.mongodb.spring.example.aggregation.TestAggregationFramework.java

/**
 * Example taken from http://docs.mongodb.org/manual/tutorial/aggregation-examples/#aggregations-using-the-zip-code-data-set
 * Command line import: mongoimport --drop -d aggregation_test_db -c zipcodes zips.json
 * <p>//from  www .  j  a  v  a  2  s  .  co  m
 *      db.zipcodes.aggregate(  { $group : { _id : "$state", totalPop : { $sum : "$pop" } } },
 *                              { $match : {totalPop : { $gt : 10*1000*1000 } } } )
 * </p>
 */
@Test
public void shouldFindAllStatesWithPopulationOver10Millions() {
    //GIVEN
    CollectionManager.cleanAndFill(mongoTemplate.getDb(), "zips.json", ZipData.COLLECTION_NAME);
    int lowerLimit = 10 * 1000 * 1000;

    //WHEN
    AggregationResults<AggregatedStateData> aggregationResult = mongoTemplate.aggregate(
            Aggregation.newAggregation(StateData.class, Aggregation.group("state").sum("population").as("pop"),
                    Aggregation.match(Criteria.where("pop").gt(lowerLimit))),
            AggregatedStateData.class);

    //THEN
    assertThat(aggregationResult.getMappedResults()).hasSize(7);
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * Filter for Data-related books in their title and output the title and authors.
 *///w  w w  . jav  a2 s .c om
@Test
public void shouldRetrieveDataRelatedBooks() {

    Aggregation aggregation = newAggregation( //
            match(Criteria.where("volumeInfo.title").regex("data", "i")), //
            replaceRoot("volumeInfo"), //
            project("title", "authors"), //
            sort(Direction.ASC, "title"));

    AggregationResults<BookAndAuthors> result = operations.aggregate(aggregation, "books",
            BookAndAuthors.class);

    BookAndAuthors bookAndAuthors = result.getMappedResults().get(1);

    assertThat(bookAndAuthors.getTitle()).isEqualTo("Spring Data");
    assertThat(bookAndAuthors.getAuthors()).contains("Mark Pollack", "Oliver Gierke", "Thomas Risberg",
            "Jon Brisbin", "Michael Hunger");
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * Retrieve the number of pages per author (and divide the number of pages by the number of authors).
 *//*from   w  ww .ja va 2 s  . co m*/
@Test
public void shouldRetrievePagesPerAuthor() {

    Aggregation aggregation = newAggregation( //
            match(Criteria.where("volumeInfo.authors").exists(true)), //
            replaceRoot("volumeInfo"), //
            project("authors", "pageCount") //
                    .and(ArithmeticOperators.valueOf("pageCount") //
                            .divideBy(ArrayOperators.arrayOf("authors").length()))
                    .as("pagesPerAuthor"),
            unwind("authors"), //
            group("authors") //
                    .sum("pageCount").as("totalPageCount") //
                    .sum("pagesPerAuthor").as("approxWritten"), //
            sort(Direction.DESC, "totalPageCount"));

    AggregationResults<PagesPerAuthor> result = operations.aggregate(aggregation, "books",
            PagesPerAuthor.class);

    PagesPerAuthor pagesPerAuthor = result.getMappedResults().get(0);

    assertThat(pagesPerAuthor.getAuthor()).isEqualTo("Josh Long");
    assertThat(pagesPerAuthor.getTotalPageCount()).isEqualTo(1892);
    assertThat(pagesPerAuthor.getApproxWritten()).isEqualTo(573);
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * Get number of books that were published by the particular publisher with their titles.
 *//*from w w w  . j av a 2s .  c o m*/
@Test
public void shouldRetrieveBooksPerPublisherWithTitles() {

    Aggregation aggregation = newAggregation( //
            group("volumeInfo.publisher") //
                    .count().as("count") //
                    .addToSet("volumeInfo.title").as("titles"), //
            sort(Direction.DESC, "count"), //
            project("count", "titles").and("_id").as("publisher"));

    AggregationResults<BooksPerPublisher> result = operations.aggregate(aggregation, "books",
            BooksPerPublisher.class);

    BooksPerPublisher booksPerPublisher = result.getMappedResults().get(0);

    assertThat(booksPerPublisher.getPublisher()).isEqualTo("Apress");
    assertThat(booksPerPublisher.getCount()).isEqualTo(26);
    assertThat(booksPerPublisher.getTitles()).contains("Expert Spring MVC and Web Flow", "Pro Spring Boot");
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * Categorize books by their page count into buckets.
 *//*from  w w w  .  j a v a2s.  c om*/
@Test
public void shouldCategorizeBooksInBuckets() {

    Aggregation aggregation = newAggregation( //
            replaceRoot("volumeInfo"), //
            match(Criteria.where("pageCount").exists(true)), bucketAuto("pageCount", 10) //
                    .withGranularity(Granularities.SERIES_1_2_5) //
                    .andOutput("title").push().as("titles") //
                    .andOutput("titles").count().as("count"));

    AggregationResults<BookFacetPerPage> result = operations.aggregate(aggregation, "books",
            BookFacetPerPage.class);

    List<BookFacetPerPage> mappedResults = result.getMappedResults();

    BookFacetPerPage facet_20_to_100_pages = mappedResults.get(0);
    assertThat(facet_20_to_100_pages.getMin()).isEqualTo(20);
    assertThat(facet_20_to_100_pages.getMax()).isEqualTo(100);
    assertThat(facet_20_to_100_pages.getCount()).isEqualTo(12);

    BookFacetPerPage facet_100_to_500_pages = mappedResults.get(1);
    assertThat(facet_100_to_500_pages.getMin()).isEqualTo(100);
    assertThat(facet_100_to_500_pages.getMax()).isEqualTo(500);
    assertThat(facet_100_to_500_pages.getCount()).isEqualTo(63);
    assertThat(facet_100_to_500_pages.getTitles()).contains("Spring Data");
}

From source file:eu.cloudwave.wp5.feedbackhandler.advices.RuntimeDataProviderImpl.java

/**
 * {@inheritDoc}/*ww w .j  a v  a  2s . c om*/
 */
@Override
public List<AggregatedProcedureMetricsDto> hotspots(final DbApplication application, final double threshold) {
    final AggregationResults<ProcedureMetricAggregation> averageExecutionTimes = getAggregatedValues(
            application, MetricTypeImpl.EXECUTION_TIME);
    final AggregationResults<ProcedureMetricAggregation> averageCpuUsageValues = getAggregatedValues(
            application, MetricTypeImpl.CPU_USAGE);
    final List<AggregatedProcedureMetricsDto> aggregationDtos = metricDtoFactory
            .create(averageExecutionTimes.getMappedResults(), averageCpuUsageValues.getMappedResults());
    return filterWithThreshold(aggregationDtos, threshold);
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from  w w w  .  ja v a2s .  co m
public List<String> findDistinctValues(String launchId, String containsValue, String distinctBy) {
    Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).is(launchId)), unwind(distinctBy),
            match(where(distinctBy).regex("(?i).*" + Pattern.quote(containsValue) + ".*")), group(distinctBy));
    AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, TestItem.class, Map.class);
    return result.getMappedResults().stream().map(entry -> entry.get("_id").toString()).collect(toList());
}