Java Code Examples for org.springframework.data.mongodb.core.aggregation.AggregationResults#getMappedResults()

The following examples show how to use org.springframework.data.mongodb.core.aggregation.AggregationResults#getMappedResults() . 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: ArticleCommentRepositoryImpl.java    From jakduk-api with MIT License 8 votes vote down vote up
/**
 * 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 2
Source File: ReviewRepositoryImpl.java    From mirrorgate with Apache License 2.0 8 votes vote down vote up
@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: VideoServiceImpl.java    From biliob_backend with MIT License 7 votes vote down vote up
/**
 * 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 4
Source File: ArticleCommentRepositoryImpl.java    From jakduk-api with MIT License 7 votes vote down vote up
/**
 * 게시물 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 5
Source File: MySpringBootApplicationTests.java    From spring-boot-101 with Apache License 2.0 7 votes vote down vote up
@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 6
Source File: DependencySimilarityCalculator.java    From scava with Eclipse Public License 2.0 7 votes vote down vote up
@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 7
Source File: DependencySimilarityCalculator.java    From scava with Eclipse Public License 2.0 7 votes vote down vote up
@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 8
Source File: JakdukDAO.java    From jakduk-api with MIT License 7 votes vote down vote up
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: IndexServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
@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 10
Source File: ReviewRepositoryImpl.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@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 11
Source File: ArticleCommentRepositoryImpl.java    From jakduk-api with MIT License 6 votes vote down vote up
/**
 * 기준 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 12
Source File: ServiceRepositoryImpl.java    From microcks with Apache License 2.0 5 votes vote down vote up
public List<LabelValues> listLabels() {
   ObjectOperators.ObjectToArray labels = ObjectOperators.ObjectToArray.valueOfToArray("metadata.labels");
   Aggregation aggregation = newAggregation(
         project().and(labels).as("labels"),
         unwind("labels"),
         sort(DESC, "labels.v"),
         group("labels.k")
               .addToSet("labels.v").as("values")
               .first("labels.k").as("key")
   );
   AggregationResults<LabelValues> results = template.aggregate(aggregation, Service.class, LabelValues.class);
   return results.getMappedResults();
}
 
Example 13
Source File: UserInfoServiceImpl.java    From ExecDashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getFrequentExecutives() {
	List<String> executives = new LinkedList<>();
	try {
		Map<String, Integer> resultsMap = new HashMap<>();
		Map<String, Integer> resultsMapSorted = new LinkedHashMap<>();
		List<String> views = new ArrayList<>();
		views.add(PORTFOLIO);
		views.add(PORTFOLIOMETRIC);
		GroupOperation groupByExecutiveViewId = Aggregation.group(EXECUTIVEVIEWID).count().as(TOTAL);
		MatchOperation filter = Aggregation.match(new Criteria(VIEW).in(views).andOperator(
				Criteria.where(TIMESTAMP).gte(getTimeStamp(30)), Criteria.where(EXECUTIVEVIEWID).ne(null)));
		Aggregation aggregation = Aggregation.newAggregation(filter, groupByExecutiveViewId);
		AggregationResults<DBObject> temp = mongoTemplate.aggregate(aggregation, TRACKVIEWS, DBObject.class);
		if (temp != null) {
			List<DBObject> results = temp.getMappedResults();
			if (results != null && !results.isEmpty()) {
				for (DBObject object : results) {
					if (object.get(FIRSTORDER) != null) {
						String id = object.get(FIRSTORDER).toString();
						Integer total = (Integer) object.get(TOTAL);
						resultsMap.put(id, total);
					}
				}
				resultsMap.entrySet().stream().sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
						.forEachOrdered(x -> resultsMapSorted.put(x.getKey(), x.getValue()));
				resultsMapSorted.forEach((eid, v) -> {
					ExecutiveSummaryList executive = executiveSummaryListRepository.findByEid(eid);
					if (executive != null) {
						executives.add(executive.getFirstName() + ", " + executive.getLastName());
					}
				});
			}
		}
	} catch (Exception e) {
		LOG.error("User Tracking, getFrequentExecutives :: " + e);
	}
	return executives;
}
 
Example 14
Source File: ServiceRepositoryImpl.java    From microcks with Apache License 2.0 5 votes vote down vote up
public List<ServiceCount> countServicesByType() {
   Aggregation aggregation = newAggregation(
         project("type"),
         group("type").count().as("number"),
         project("number").and("type").previousOperation(),
         sort(DESC, "number")
   );
   AggregationResults<ServiceCount> results = template.aggregate(aggregation, Service.class, ServiceCount.class);
   return results.getMappedResults();
}
 
Example 15
Source File: DashboardRepositoryImpl.java    From mirrorgate with Apache License 2.0 5 votes vote down vote up
private List<Dashboard> getDashboardsNotInStatus(final DashboardStatus... status) {
    final Aggregation aggregation = newAggregation(
        sort(Sort.by(Sort.Direction.DESC, "lastModification")),
        firstDashboardFields(group("name")),
        match(Criteria.where("status").nin(Collections.singletonList(status))),
        project(DASHBOARD_FIELDS.keySet().toArray(new String[]{})).andExclude("_id")
    );

    //Convert the aggregation result into a List
    final AggregationResults<Dashboard> groupResults
        = mongoTemplate.aggregate(aggregation, Dashboard.class, Dashboard.class);

    return groupResults.getMappedResults();
}
 
Example 16
Source File: UserMetricsRepositoryImpl.java    From mirrorgate with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserMetric> findAllStartingWithViewId(final List<String> viewIds) {

    final Aggregation agg = newAggregation(
        match(getCriteriaExpressionsForUserMetrics(viewIds))
    );

    final AggregationResults<UserMetric> aggregationResult
        = mongoTemplate.aggregate(agg, UserMetric.class, UserMetric.class);

    return aggregationResult.getMappedResults();
}
 
Example 17
Source File: SpringBooksIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 18
Source File: UserInfoServiceImpl.java    From ExecDashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getFrequentCards() {
	List<String> metrics = new LinkedList<>();
	try {
		Map<String, Integer> resultsMap = new HashMap<>();
		Map<String, Integer> resultsMapSorted = new LinkedHashMap<>();
		List<String> views = new ArrayList<>();
		views.add(PRODUCTMETRIC);
		views.add(PORTFOLIOMETRIC);
		GroupOperation groupByApplicationViewId = Aggregation.group(METRICSNAME).count().as(TOTAL);
		MatchOperation filter = Aggregation.match(new Criteria(VIEW).in(views).andOperator(
				Criteria.where(TIMESTAMP).gte(getTimeStamp(30)), Criteria.where(METRICSNAME).ne(null)));
		Aggregation aggregation = Aggregation.newAggregation(filter, groupByApplicationViewId);
		AggregationResults<DBObject> temp = mongoTemplate.aggregate(aggregation, TRACKVIEWS, DBObject.class);
		if (temp != null) {
			List<DBObject> results = temp.getMappedResults();
			if (results != null && !results.isEmpty()) {
				for (DBObject object : results) {
					if (object.get(ID) != null) {
						String id = object.get(ID).toString();
						Integer total = (Integer) object.get(TOTAL);
						resultsMap.put(id, total);
					}
				}
				resultsMap.entrySet().stream().sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
						.forEachOrdered(x -> resultsMapSorted.put(x.getKey(), x.getValue()));
				resultsMapSorted.forEach((k, v) -> metrics.add(k));
			}
		}
	} catch (Exception e) {
		LOG.error("User Tracking, getFrequentCards :: " + e);
	}
	return metrics;
}
 
Example 19
Source File: UserInfoServiceImpl.java    From ExecDashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getFrequentApplications() {
	List<String> applications = new LinkedList<>();
	try {
		Map<String, Integer> resultsMap = new HashMap<>();
		Map<String, Integer> resultsMapSorted = new LinkedHashMap<>();
		List<String> views = new ArrayList<>();
		views.add(PRODUCTMETRIC);
		views.add(PRODUCT);
		GroupOperation groupByApplicationViewId = Aggregation.group(APPLICATIONVIEWID).count().as(TOTAL);
		MatchOperation filter = Aggregation.match(new Criteria(VIEW).in(views).andOperator(
				Criteria.where(TIMESTAMP).gte(getTimeStamp(30)), Criteria.where(APPLICATIONVIEWID).ne(null)));
		Aggregation aggregation = Aggregation.newAggregation(filter, groupByApplicationViewId);
		AggregationResults<DBObject> temp = mongoTemplate.aggregate(aggregation, TRACKVIEWS, DBObject.class);
		if (temp != null) {
			List<DBObject> results = temp.getMappedResults();
			if (results != null && !results.isEmpty()) {
				for (DBObject object : results) {
					if (object.get(FIRSTORDER) != null) {
						String id = object.get(FIRSTORDER).toString();
						Integer total = (Integer) object.get(TOTAL);
						resultsMap.put(id, total);
					}
				}
				resultsMap.entrySet().stream().sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
						.forEachOrdered(x -> resultsMapSorted.put(x.getKey(), x.getValue()));
				resultsMapSorted.forEach((appId, v) -> {
					ApplicationDetails app = applicationDetailsRepository.findByAppId(appId);
					if (app != null) {
						applications.add(app.getAppName() + " - " + app.getLob());
					}
				});
			}
		}
	} catch (Exception e) {
		LOG.error("User Tracking, getFrequentApplications :: " + e);
	}
	return applications;
}
 
Example 20
Source File: BuildRepositoryImpl.java    From mirrorgate with Apache License 2.0 4 votes vote down vote up
@Override
public List<Build> findLastBuildsByKeywordsAndByTeamMembers(
    final List<String> keywords,
    final List<String> teamMembers
) {
    final TypedAggregation<Build> agg = newAggregation(Build.class,
        match(new Criteria()
            .andOperator(
                getCriteriaExpressionsForKeywords(keywords),
                getCriteriaExpressionsForTeamMembers(teamMembers),
                Criteria.where("buildStatus")
                    .nin(
                        BuildStatus.Aborted.toString(),
                        BuildStatus.NotBuilt.toString(),
                        BuildStatus.Unknown.toString()
                    )
            )
            .orOperator(
                Criteria.where("latest")
                    .is(true)
                    .and("buildStatus").ne(BuildStatus.Deleted.toString()),
                Criteria.where("timestamp")
                    .gt(System.currentTimeMillis() - 24 * 3600 * 1000)
            )
        ),
        //Avoid Mongo to "optimize" the sort operation... Why Mongo, oh why?!
        project("buildStatus", "branch", "projectName", "repoName",
            "timestamp", "buildUrl", "duration", "startTime",
            "endTime", "culprits")
            .andExclude("_id"),
        sort(Sort.Direction.ASC, "timestamp"),
        group("branch", "repoName", "projectName")
            .last("buildStatus").as("buildStatus")
            .last("repoName").as("repoName")
            .last("timestamp").as("timestamp")
            .last("buildUrl").as("buildUrl")
            .last("branch").as("branch")
            .last("startTime").as("startTime")
            .last("endTime").as("endTime")
            .last("duration").as("duration")
            .last("projectName").as("projectName")
            .last("culprits").as("culprits"),
        match(Criteria.where("buildStatus").ne(
            BuildStatus.Deleted.toString())),
        project("buildStatus", "branch", "projectName", "repoName",
            "timestamp", "buildUrl", "duration", "startTime",
            "endTime", "culprits")
            .andExclude("_id")
    );

    //Convert the aggregation result into a List
    final AggregationResults<Build> groupResults
        = mongoTemplate.aggregate(agg, Build.class);

    return groupResults.getMappedResults();

}