org.springframework.data.mongodb.core.aggregation.AggregationResults Java Examples
The following examples show how to use
org.springframework.data.mongodb.core.aggregation.AggregationResults.
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: GalleryOnListTest.java From jakduk-api with MIT License | 10 votes |
@Test public void findById() { ArrayList<ObjectId> arrTemp = new ArrayList<ObjectId>(); arrTemp.add(new ObjectId("54c4df893d96600d7f55a048")); arrTemp.add(new ObjectId("54c4e4833d96deb0f8592907")); AggregationOperation match = Aggregation.match(Criteria.where("_id").in(arrTemp)); //AggregationOperation group = Aggregation.group("article").count().as("count"); AggregationOperation sort = Aggregation.sort(Direction.ASC, "_id"); //AggregationOperation limit = Aggregation.limit(Constants.BOARD_LINE_NUMBER); Aggregation aggregation = Aggregation.newAggregation(match, /*group, */ sort /*, limit*/); AggregationResults<Gallery> results = mongoTemplate.aggregate(aggregation, "gallery", Gallery.class); System.out.println("findOneById=" + results.getMappedResults()); }
Example #2
Source File: ReviewRepositoryImpl.java From mirrorgate with Apache License 2.0 | 8 votes |
@Override public List<ApplicationDTO> getAverageRateByAppNamesAfterTimestamp(final List<String> names, final Long timestamp) { final Aggregation aggregation = newAggregation( match(Criteria.where("appname").in(names).and("timestamp").gte(timestamp)), group("appname", "platform") .first("appname").as("appname") .first("platform").as("platform") .count().as("votesShortTerm") .sum("starrating").as("ratingShortTerm") ); //Convert the aggregation result into a List final AggregationResults<ApplicationDTO> groupResults = mongoTemplate.aggregate(aggregation, Review.class, ApplicationDTO.class); return groupResults.getMappedResults(); }
Example #3
Source File: ArticleCommentRepositoryImpl.java From jakduk-api with MIT License | 8 votes |
/** * boardItem의 boardId 기준 이상의 댓글 수를 가져온다 * * @param boardId 기준이 되는 boardItem의 boardId */ @Override public List<CommonCount> findCommentsCountGreaterThanBoardIdAndBoard(ObjectId boardId, Constants.BOARD_TYPE board) { AggregationOperation match1 = Aggregation.match(Criteria.where("article._id").gt(boardId).and("article.board").is(board.name())); AggregationOperation group = Aggregation.group("article").count().as("count"); AggregationOperation sort = Aggregation.sort(Sort.Direction.DESC, "count"); //AggregationOperation limit = Aggregation.limit(Constants.BOARD_TOP_LIMIT); Aggregation aggregation = Aggregation.newAggregation(match1, group, sort/*, limit*/); AggregationResults<CommonCount> results = mongoTemplate.aggregate(aggregation, Constants.COLLECTION_ARTICLE_COMMENT, CommonCount.class); return results.getMappedResults(); }
Example #4
Source File: IssueRepositoryImpl.java From mirrorgate with Apache License 2.0 | 7 votes |
@Override public double getBacklogEstimateByKeywords(final List<String> boards) { final Aggregation agg = newAggregation( match(Criteria .where("keywords").in(boards) .and("sprintAssetState").ne("ACTIVE") .and("type").in(Arrays.asList(IssueType.STORY.getName(), IssueType.BUG.getName())) .and("status").nin(Arrays.asList(IssueStatus.ACCEPTED.getName(), IssueStatus.DONE.getName())) ), group() .sum("estimation") .as("value"), project("value") .andExclude("_id") ); final AggregationResults<DoubleValue> groupResults = mongoTemplate.aggregate(agg, "issue", DoubleValue.class); final DoubleValue val = groupResults.getUniqueMappedResult(); return val == null ? 0 : val.value; }
Example #5
Source File: ReviewRepositoryImpl.java From mirrorgate with Apache License 2.0 | 7 votes |
@Override public List<ApplicationDTO> getAppInfoByAppNames(final List<String> names) { final Aggregation aggregation = newAggregation( match(Criteria.where("appname").in(names).and("timestamp").exists(true)), sort(Sort.by(DESC, "timestamp")), project("appname", "platform", "starrating", "timestamp", "comment", "authorName", "url"), group("appname", "platform") .push(new BasicDBObject("author", "$authorName") .append("rate", "$starrating") .append("timestamp", "$timestamp") .append("comment", "$comment") .append("url", "$url") ).as("reviews"), project("appname", "platform") .and("reviews").slice(8, 0) ); //Convert the aggregation result into a List final AggregationResults<ApplicationDTO> groupResults = mongoTemplate.aggregate(aggregation, Review.class, ApplicationDTO.class); return groupResults.getMappedResults(); }
Example #6
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 7 votes |
/** * Retrieve the number of pages per author (and divide the number of pages by the number of authors). */ @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); }
Example #7
Source File: CommitRepositoryImpl.java From mirrorgate with Apache License 2.0 | 7 votes |
@Override public Double getSecondsToMaster(final List<String> repositories, final long timestamp) { final Aggregation agg = newAggregation( match(getCriteriaExpressionsForRepositories(repositories) .and("timestamp").gte(timestamp) ), group() .avg( Ceil.ceilValueOf( Subtract.valueOf("$branches.refs/remotes/origin/master").subtract("timestamp") ) ).as("value"), project("value") .andExclude("_id") ); final AggregationResults<DoubleValue> secondsToMaster = mongoTemplate .aggregate(agg, "commits", DoubleValue.class); final DoubleValue seconds = secondsToMaster.getUniqueMappedResult(); return seconds != null ? seconds.value : null; }
Example #8
Source File: JakdukDAO.java From jakduk-api with MIT License | 7 votes |
public List<SupporterCount> getSupportFCCount(String language) { AggregationOperation match = Aggregation.match(Criteria.where("supportFC").exists(true)); AggregationOperation group = Aggregation.group("supportFC").count().as("count"); AggregationOperation project = Aggregation.project("count").and("_id").as("supportFC"); AggregationOperation sort = Aggregation.sort(Direction.DESC, "count"); Aggregation aggregation = Aggregation.newAggregation(match, group, project, sort); AggregationResults<SupporterCount> results = mongoTemplate.aggregate(aggregation, "user", SupporterCount.class); List<SupporterCount> users = results.getMappedResults(); for (SupporterCount supporterCount : users) { supporterCount.getSupportFC().getNames().removeIf(fcName -> !fcName.getLanguage().equals(language)); } return users; }
Example #9
Source File: DependencySimilarityCalculator.java From scava with Eclipse Public License 2.0 | 7 votes |
@Override public int getNumberOfProjectThatUseDependencies(String dependency) { Aggregation aggregation = newAggregation( unwind("dependencies"), group("dependencies").count().as("count"), project("count").and("dependencies").previousOperation(), sort(Direction.DESC,"count"), match(Criteria.where("dependencies").is(dependency)) ); AggregationResults<DependencyCount> results = mongoOperations.aggregate(aggregation, "artifact", DependencyCount.class); List<DependencyCount> result = results.getMappedResults(); if(!result.isEmpty()) return result.get(0).getCount(); else return 0; }
Example #10
Source File: IssueRepositoryImpl.java From mirrorgate with Apache License 2.0 | 7 votes |
@Override public ProgramIncrementNamesAggregationResult getProductIncrementFromPiPattern(final Pattern pi) { final Aggregation agg = newAggregation( match(Criteria .where("type").is(IssueType.FEATURE.getName()) ), project("piNames").andExclude("_id"), unwind("piNames"), match(Criteria .where("piNames").is(pi) ), group().addToSet("piNames").as("piNames") ); final AggregationResults<ProgramIncrementNamesAggregationResult> aggregationResult = mongoTemplate.aggregate(agg, "issue", ProgramIncrementNamesAggregationResult.class); return aggregationResult.getUniqueMappedResult(); }
Example #11
Source File: IssueRepositoryImpl.java From mirrorgate with Apache License 2.0 | 7 votes |
@Override public List<String> programIncrementBoardFeatures( final List<String> boards, final List<String> programIncrementFeatures ) { final Aggregation agg = newAggregation( match(Criteria .where("parentsKeys").in(programIncrementFeatures) .and("keywords").in(boards) ), unwind("parentsKeys"), group() .addToSet("parentsKeys") .as("features"), project("features") .andExclude("_id") ); final AggregationResults<ProgramIncrementBoardFeatures> aggregationResult = mongoTemplate.aggregate(agg, "issue", ProgramIncrementBoardFeatures.class); return aggregationResult.getUniqueMappedResult() != null ? aggregationResult.getUniqueMappedResult().features : new ArrayList<>(); }
Example #12
Source File: ArticleCommentRepositoryImpl.java From jakduk-api with MIT License | 7 votes |
/** * 게시물 ID 에 해당하는 댓글 수를 가져온다. */ @Override public List<CommonCount> findCommentsCountByIds(List<ObjectId> ids) { AggregationOperation match = Aggregation.match(Criteria.where("article._id").in(ids)); AggregationOperation group = Aggregation.group("article").count().as("count"); //AggregationOperation sort = Aggregation.sort(Direction.ASC, "_id"); //AggregationOperation limit = Aggregation.limit(Constants.BOARD_LINE_NUMBER); Aggregation aggregation = Aggregation.newAggregation(match, group/*, sort, limit*/); AggregationResults<CommonCount> results = mongoTemplate.aggregate(aggregation, Constants.COLLECTION_ARTICLE_COMMENT, CommonCount.class); return results.getMappedResults(); }
Example #13
Source File: VideoServiceImpl.java From biliob_backend with MIT License | 7 votes |
/** * Get top online video in one day. * * @return top online video response. */ @Override public ResponseEntity listOnlineVideo() { Calendar todayStart = Calendar.getInstance(); todayStart.add(Calendar.DATE, -1); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("data.datetime").gt(todayStart.getTime())), Aggregation.limit(20), Aggregation.project("title", "author") .and("data") .filter( "item", ComparisonOperators.Gte.valueOf("$$item.datetime") .greaterThanEqualToValue(todayStart.getTime())) .as("$data")); AggregationResults<VideoOnline> aggregationResults = mongoTemplate.aggregate(aggregation, "video_online", VideoOnline.class); List<VideoOnline> videoOnlineList = aggregationResults.getMappedResults(); return new ResponseEntity<>(videoOnlineList, HttpStatus.OK); }
Example #14
Source File: TracerServiceImpl.java From biliob_backend with MIT License | 7 votes |
private void getCrawlCountAggregationData(Map<String, Object> resultMap) { Aggregation crawlCountAggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("class_name").is("SpiderTask")), Aggregation.group("class_name").sum("crawl_count").as("sumCrawlCount")); AggregationResults<Map> crawlCountAggregationResult = mongoTemplate.aggregate(crawlCountAggregation, "tracer", Map.class); resultMap.putAll(Objects.requireNonNull(crawlCountAggregationResult.getUniqueMappedResult())); }
Example #15
Source File: DependencySimilarityCalculator.java From scava with Eclipse Public License 2.0 | 7 votes |
@Override public Map<String, Integer> getMapDependencyAndNumOfProjectThatUseIt() { Map<String, Integer> result = new HashMap<>(); Aggregation aggregation = newAggregation( unwind("dependencies"), group("dependencies").count().as("count"), project("count").and("dependencies").previousOperation(), sort(Direction.DESC,"count") ); AggregationResults<DependencyCount> results = mongoOperations.aggregate(aggregation, "artifact", DependencyCount.class); List<DependencyCount> intermediateResult = results.getMappedResults(); for (DependencyCount dependencyCount : intermediateResult) { result.put(dependencyCount.getDependencies(), dependencyCount.getCount()); } return result; }
Example #16
Source File: TxManagerInfoServiceImpl.java From Lottor with MIT License | 7 votes |
/** * 按照日期获取tx的数量 * * @return */ @Override public Map<String, String> clientDetails(Boolean source) { Map<String, String> res = new HashMap<>(); String attr = source ? "source" : "target"; Arrays.stream(ServiceNameEnum.values()).forEach(serviceNameEnum -> { String service = serviceNameEnum.getServiceName(); Aggregation aggregation = Aggregation.newAggregation( match(new Criteria(attr).is(service)), group(attr).count().as("count") ); AggregationResults<BasicDBObject> results = mongoTemplate.aggregate(aggregation, CollectionNameEnum.TransactionMsg.name(), BasicDBObject.class); List<BasicDBObject> dbObjects = results.getMappedResults(); for (int i = 0; i < dbObjects.size(); i++) { BasicDBObject data = dbObjects.get(i); res.put(data.getString("_id"), data.getString("count")); } }); return res; }
Example #17
Source File: MySpringBootApplicationTests.java From spring-boot-101 with Apache License 2.0 | 7 votes |
@Test public void mongoAggregationTest() throws JsonProcessingException{ Criteria c = new Criteria(); c.and("sex").is("F"); Aggregation aggr = Aggregation.newAggregation( Aggregation.match(c), Aggregation.group("lastName").count().as("count") ); AggregationResults<BasicDBObject> aggrResult = mongoTemplate.aggregate(aggr, "person", BasicDBObject.class); if(!aggrResult.getMappedResults().isEmpty()){ for(BasicDBObject obj : aggrResult.getMappedResults()){ logger.info("count by first name: {}", objectMapper.writeValueAsString(obj)); } } }
Example #18
Source File: OrderRepositoryImpl.java From spring-data-examples with Apache License 2.0 | 6 votes |
/** * The implementation uses the MongoDB aggregation framework support Spring Data provides as well as SpEL expressions * to define arithmetical expressions. Note how we work with property names only and don't have to mitigate the nested * {@code $_id} fields MongoDB usually requires. * * @see example.springdata.mongodb.aggregation.OrderRepositoryCustom#getInvoiceFor(example.springdata.mongodb.aggregation.Order) */ @Override public Invoice getInvoiceFor(Order order) { AggregationResults<Invoice> results = operations.aggregate(newAggregation(Order.class, // match(where("id").is(order.getId())), // unwind("items"), // project("id", "customerId", "items") // .andExpression("'$items.price' * '$items.quantity'").as("lineTotal"), // group("id") // .sum("lineTotal").as("netAmount") // .addToSet("items").as("items"), // project("id", "items", "netAmount") // .and("orderId").previousOperation() // .andExpression("netAmount * [0]", taxRate).as("taxAmount") // .andExpression("netAmount * (1 + [0])", taxRate).as("totalAmount") // ), Invoice.class); return results.getUniqueMappedResult(); }
Example #19
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 6 votes |
/** * Filter for Data-related books in their title and output the title and authors. */ @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"); }
Example #20
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 6 votes |
/** * Get number of books that were published by the particular publisher with their titles. */ @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"); }
Example #21
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 6 votes |
/** * Get number of books that were published by the particular publisher. */ @Test public void shouldRetrieveBooksPerPublisher() { Aggregation aggregation = newAggregation( // group("volumeInfo.publisher") // .count().as("count"), // sort(Direction.DESC, "count"), // project("count").and("_id").as("publisher")); AggregationResults<BooksPerPublisher> result = operations.aggregate(aggregation, "books", BooksPerPublisher.class); assertThat(result).hasSize(27); assertThat(result).extracting("publisher").containsSequence("Apress", "Packt Publishing Ltd"); assertThat(result).extracting("count").containsSequence(26, 22, 11); }
Example #22
Source File: ReviewRepositoryImpl.java From mirrorgate with Apache License 2.0 | 6 votes |
@Override public List<ApplicationReviewsDTO> getLastReviewPerApplication(final List<String> names) { final Aggregation aggregation = newAggregation( match(Criteria.where("appname").in(names)), sort(Sort.by(DESC, "timestamp")), group("appname", "platform") .first("platform").as("platform") .first("appname").as("appName") .first("appname").as("appId") .first("commentId").as("commentId") ); //Convert the aggregation result into a List final AggregationResults<ApplicationReviewsDTO> groupResults = mongoTemplate.aggregate(aggregation, Review.class, ApplicationReviewsDTO.class); return groupResults.getMappedResults(); }
Example #23
Source File: CommitRepositoryImpl.java From mirrorgate with Apache License 2.0 | 6 votes |
@Override public Double getCommitsPerDay(final List<String> repositories, final long timestamp, final int daysBefore) { final Aggregation agg = newAggregation( match(getCriteriaExpressionsForRepositories(repositories) .and("timestamp").gte(timestamp) ), group() .count().as("value"), project("value") .andExclude("_id").and("value").divide(daysBefore) ); final AggregationResults<DoubleValue> commitsPerDay = mongoTemplate.aggregate(agg, "commits", DoubleValue.class); final DoubleValue commits = commitsPerDay.getUniqueMappedResult(); return commits != null ? commits.value : null; }
Example #24
Source File: JakdukDAO.java From jakduk-api with MIT License | 6 votes |
public List<JakduComment> getJakduComments(String jakduScheduleId, ObjectId commentId) { AggregationOperation match1 = Aggregation.match(Criteria.where("jakduScheduleId").is(jakduScheduleId)); AggregationOperation match2 = Aggregation.match(Criteria.where("_id").gt(commentId)); AggregationOperation sort = Aggregation.sort(Direction.ASC, "_id"); AggregationOperation limit = Aggregation.limit(Constants.COMMENT_MAX_LIMIT); Aggregation aggregation; if (Objects.nonNull(commentId)) { aggregation = Aggregation.newAggregation(match1, match2, sort, limit); } else { aggregation = Aggregation.newAggregation(match1, sort, limit); } AggregationResults<JakduComment> results = mongoTemplate.aggregate(aggregation, "jakduComment", JakduComment.class); List<JakduComment> comments = results.getMappedResults(); return comments; }
Example #25
Source File: ArticleCommentRepositoryImpl.java From jakduk-api with MIT License | 6 votes |
/** * 기준 ArticleComment ID 이상의 ArticleComment 목록을 가져온다. */ @Override public List<ArticleComment> findCommentsGreaterThanId(ObjectId objectId, Integer limit) { AggregationOperation match1 = Aggregation.match(Criteria.where("_id").gt(objectId)); AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "_id"); AggregationOperation limit1 = Aggregation.limit(limit); Aggregation aggregation; if (! ObjectUtils.isEmpty(objectId)) { aggregation = Aggregation.newAggregation(match1, sort, limit1); } else { aggregation = Aggregation.newAggregation(sort, limit1); } AggregationResults<ArticleComment> results = mongoTemplate.aggregate(aggregation, Constants.COLLECTION_ARTICLE_COMMENT, ArticleComment.class); return results.getMappedResults(); }
Example #26
Source File: IndexServiceImpl.java From biliob_backend with MIT License | 6 votes |
@Override @Cacheable(value = "jannchie-index-recently-rank") public List<?> getRecentlyRank() { logger.info("获取近期(7日内)热门指数"); List<HashMap<?, ?>> data = (List<HashMap<?, ?>>) videoService.getPopularTag(); List<HashMap> modifiableList = new ArrayList<>(data); modifiableList.sort(Comparator.comparing(e -> (Integer) e.get("value"))); Object[] tagArray = modifiableList.stream().map(e -> (String) e.get("_id")).toArray(); ArrayList<Object> al = new ArrayList<>(Arrays.asList(tagArray).subList(0, 8)); Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -7); AggregationResults<?> ar = mongoTemplate.aggregate( Aggregation.newAggregation( Aggregation.unwind("tag"), Aggregation.match(Criteria.where("tag").in(al).and("datetime").gt(c.getTime())), Aggregation.group("tag").sum("cJannchie").as("jannchie"), Aggregation.project("jannchie").and("_id").as("tag") ), Video.class, HashMap.class ); return ar.getMappedResults(); }
Example #27
Source File: ZipsAggregationLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void whenStateWithLowestAvgCityPopIsND_theSuccess() { GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop"); GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop"); SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop")); ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state") .andExpression("avgCityPop").as("statePop"); LimitOperation limitToOnlyFirstDoc = limit(1); Aggregation aggregation = newAggregation(sumTotalCityPop, averageStatePop, sortByAvgPopAsc, limitToOnlyFirstDoc, projectToMatchModel); AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class); StatePopulation smallestState = result.getUniqueMappedResult(); assertEquals("ND", smallestState.getState()); assertTrue(smallestState.getStatePop() .equals(1645)); }
Example #28
Source File: ZipsAggregationLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void whenMaxTXAndMinDC_theSuccess() { GroupOperation sumZips = group("state").count().as("zipCount"); SortOperation sortByCount = sort(Direction.ASC, "zipCount"); GroupOperation groupFirstAndLast = group().first("_id").as("minZipState") .first("zipCount").as("minZipCount").last("_id").as("maxZipState") .last("zipCount").as("maxZipCount"); Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast); AggregationResults<Document> result = mongoTemplate.aggregate(aggregation, "zips", Document.class); Document document = result.getUniqueMappedResult(); assertEquals("DC", document.get("minZipState")); assertEquals(24, document.get("minZipCount")); assertEquals("TX", document.get("maxZipState")); assertEquals(1671, document.get("maxZipCount")); }
Example #29
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 5 votes |
/** * Run a multi-faceted aggregation to get buckets by price (1-10, 10-50, 50-100 EURO) and by the first letter of the * author name. */ @Test @SuppressWarnings("unchecked") public void shouldCategorizeInMultipleFacetsByPriceAndAuthor() { Aggregation aggregation = newAggregation( // match(Criteria.where("volumeInfo.authors").exists(true).and("volumeInfo.publisher").exists(true)), facet() // .and(match(Criteria.where("saleInfo.listPrice").exists(true)), // replaceRoot("saleInfo"), // bucket("listPrice.amount") // .withBoundaries(1, 10, 50, 100)) .as("prices") // .and(unwind("volumeInfo.authors"), // replaceRoot("volumeInfo"), // match(Criteria.where("authors").not().size(0)), // project() // .andExpression("substrCP(authors, 0, 1)").as("startsWith") // .and("authors").as("author"), // bucketAuto("startsWith", 10) // .andOutput("author").push().as("authors") // ).as("authors")); AggregationResults<Document> result = operations.aggregate(aggregation, "books", Document.class); Document uniqueMappedResult = result.getUniqueMappedResult(); assertThat((List<Object>) uniqueMappedResult.get("prices")).hasSize(3); assertThat((List<Object>) uniqueMappedResult.get("authors")).hasSize(8); }
Example #30
Source File: SpringBooksIntegrationTests.java From spring-data-examples with Apache License 2.0 | 5 votes |
/** * Categorize books by their page count into buckets. */ @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.getId().getMin()).isEqualTo(20); assertThat(facet_20_to_100_pages.getId().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.getId().getMin()).isEqualTo(100); assertThat(facet_100_to_500_pages.getId().getMax()).isEqualTo(500); assertThat(facet_100_to_500_pages.getCount()).isEqualTo(63); assertThat(facet_100_to_500_pages.getTitles()).contains("Spring Data"); }