Example usage for org.springframework.data.mongodb.core.aggregation Fields field

List of usage examples for org.springframework.data.mongodb.core.aggregation Fields field

Introduction

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

Prototype

public static Field field(String name, String target) 

Source Link

Document

Creates a Field with the given name and target .

Usage

From source file:org.devgateway.ocds.web.rest.controller.FrequentSuppliersTimeIntervalController.java

@ApiOperation(value = "Returns the frequent suppliers of a procuringEntity split by a time interval. "
        + "The time interval is "
        + "a parameter and represents the number of days to take as interval, starting with today and going back "
        + "till the last award date. The awards are grouped by procuringEntity, supplier and the time interval. "
        + "maxAwards parameter is used to designate what is the maximum number of awards granted to one supplier "
        + "by the same procuringEntity inside one timeInterval. The default value for maxAwards is 3 (days) and the"
        + " default value for intervalDays is 365.")
@RequestMapping(value = "/api/frequentSuppliersTimeInterval", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<FrequentSuppliersResponse> frequentSuppliersTimeInterval(
        @RequestParam(defaultValue = "365", required = false) Integer intervalDays,
        @RequestParam(defaultValue = "3", required = false) Integer maxAwards,
        @RequestParam(required = false) Date now) {

    if (now == null) {
        now = new Date();
    }/*  w  ww  .  java2 s  . c  om*/
    DBObject project = new BasicDBObject();
    project.put(MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID, 1);
    project.put(MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID, 1);
    project.put(MongoConstants.FieldNames.AWARDS_DATE, 1);
    project.put(Fields.UNDERSCORE_ID, 0);
    project.put("timeInterval",
            new BasicDBObject("$ceil",
                    new BasicDBObject("$divide",
                            Arrays.asList(
                                    new BasicDBObject("$divide",
                                            Arrays.asList(
                                                    new BasicDBObject("$subtract",
                                                            Arrays.asList(now, ref(
                                                                    MongoConstants.FieldNames.AWARDS_DATE))),
                                                    DAY_MS)),
                                    intervalDays))));

    Aggregation agg = Aggregation.newAggregation(
            match(where("tender.procuringEntity").exists(true).and("awards.suppliers.0").exists(true)
                    .and(MongoConstants.FieldNames.AWARDS_DATE).exists(true)),
            unwind("awards"), unwind("awards.suppliers"), new CustomProjectionOperation(project),
            group(Fields.from(
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID),
                    Fields.field("supplierId", MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID),
                    Fields.field("timeInterval", "timeInterval"))).count().as("count"),
            project("count").and("identifier").previousOperation(), match(where("count").gt(maxAwards)),
            sort(Sort.Direction.DESC, "count"));

    return releaseAgg(agg, FrequentSuppliersResponse.class);
}

From source file:eu.cloudwave.wp5.feedbackhandler.repositories.ProcedureExecutionRepositoryImpl.java

/**
 * {@inheritDoc}//from  w ww.ja  va2  s  .  c o m
 */
@Override
public Optional<AggregatedInvocation> getCallersOfInvokedMethod(String invokedClassName,
        String invokedMethodName, String callerClassName, String callerMethodName) {
    // objects have to have the same method name + class name
    final MatchOperation matchOperation = match(
            new Criteria(PROC__NAME).is(invokedMethodName).and(PROC__CLASS_NAME).is(invokedClassName));

    /*
     * add all distinct callers of the given invoked method to set
     * 
     * Fields.from(Fields.field(<NEW ATTRIBUTE NAME>, <ORIGINAL ATTRIBUTE NAME>))
     */
    final GroupOperation groupOperation = group(
            Fields.from(Fields.field(INVOKED_METHOD_NAME_PROJECTION, PROC__NAME))
                    .and(INVOKED_CLASS_NAME_PROJECTION, PROC__CLASS_NAME)).addToSet("$" + CALLER)
                            .as(CALLER_AGGREGATION_ATTRIBUTE);

    List<AggregatedInvocation> aggregationResults = aggregateProcedureExecution(
            newAggregation(matchOperation, groupOperation), AggregatedInvocation.class).getMappedResults();
    if (!aggregationResults.isEmpty()) {
        return Optional.of(aggregationResults.get(0));
    }
    return Optional.absent();
}

From source file:eu.cloudwave.wp5.feedbackhandler.repositories.ProcedureExecutionRepositoryImpl.java

/**
 * Helper that builds and runs the query. It creates a Match Operation, Group Operation and the Aggregation. The
 * GroupOperation groups by caller, callee, calleeMethod and method name.
 * //w w  w .  j  av  a 2  s . co  m
 * @param matchCriteria
 *          {@link Criteria} which specifies the annotation and other filters
 * @return {@link ClientRequestCollector} a list of matching requests
 */
private List<ClientRequestCollector> getRequestsWithCriteria(Criteria matchCriteria) {

    // create match operation based on input
    final MatchOperation matchOperation = match(matchCriteria);

    // 1. group by caller
    Fields fields = Fields.from(Fields.field(Ids.MICROSERVICE_CLIENT_REQUEST_ANNOTATION_FROM_ATTRIBUTE,
            "$" + ANNOTATION_FROM_ATTRIBUTE));

    // 2. group by callee
    fields = fields.and(Ids.MICROSERVICE_CLIENT_REQUEST_ANNOTATION_TO_ATTRIBUTE, "$" + ANNOTATION_TO_ATTRIBUTE);

    // 3. group by callee method
    fields = fields.and(Ids.MICROSERVICE_CLIENT_REQUEST_ANNOTATION_TO_METHOD_ATTRIBUTE,
            "$" + ANNOTATION_TO_METHOD_ATTRIBUTE);

    // 4. group by name of method that contains the invocation
    fields = fields.and(METHOD_PROJECTION, "$" + METHOD_ATTRIBUTE);

    // create group operation
    final GroupOperation groupOperation = group(fields).push("$" + TIME_FIELD).as(TIME_AGGREGATION_ATTRIBUTE);
    final Aggregation microserviceClientAggregationSpec = newAggregation(matchOperation, groupOperation);

    return aggregateProcedureExecution(microserviceClientAggregationSpec, ClientRequestCollector.class)
            .getMappedResults();
}

From source file:eu.cloudwave.wp5.feedbackhandler.repositories.ProcedureExecutionRepositoryImpl.java

/**
 * Helper that builds and runs the query. It creates a Match Operation, Group Operation and the Aggregation. The
 * GroupOperation groups by caller, callee, calleeMethod and method name.
 * /*from   www  . j a va2 s  .  com*/
 * @param matchCriteria
 *          {@link Criteria} which specifies the annotation and other filters
 * @return {@link IncomingRequestCollector} a list of matching requests
 */
private List<IncomingRequestCollector> getIncomingRequestsWithCriteria(Criteria matchCriteria,
        boolean groupByMethod) {
    // create match operation based on input
    final MatchOperation matchOperation = match(matchCriteria);

    // 1. group by service identifier
    Fields fields = Fields.from(Fields.field(Ids.MICROSERVICE_ENDPOINT_ANNOTATION_IDENTIFIER_ATTRIBUTE,
            "$" + ANNOTATION_IDENTIFIER_ATTRIBUTE));

    // 2. group by service method
    if (groupByMethod) {
        fields = fields.and(Ids.MICROSERVICE_DECLARATION_ANNOTATION_METHOD_ATTRIBUTE,
                "$" + ANNOTATION_METHOD_ATTRIBUTE);
    }

    // create group operation and push all timestamps into a list
    final GroupOperation groupOperation = group(fields).push("$" + TIME_FIELD).as(TIME_AGGREGATION_ATTRIBUTE);
    final Aggregation microserviceClientAggregationSpec = newAggregation(matchOperation, groupOperation);

    return aggregateProcedureExecution(microserviceClientAggregationSpec, IncomingRequestCollector.class)
            .getMappedResults();
}

From source file:org.devgateway.ocds.web.rest.controller.CostEffectivenessVisualsController.java

@ApiOperation(value = "Cost effectiveness of Tenders:"
        + " Displays the total amount of the active tenders that have active awards, "
        + "grouped by year. Only tenders.status=active"
        + "are taken into account. The year is calculated from tenderPeriod.startDate")
@RequestMapping(value = "/api/costEffectivenessTenderAmount", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> costEffectivenessTenderAmount(
        @ModelAttribute @Valid final GroupingFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.put("year", new BasicDBObject("$year", ref(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE)));
    addYearlyMonthlyProjection(filter, project, ref(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE));
    project.put(MongoConstants.FieldNames.TENDER_VALUE_AMOUNT, 1);
    project.put(Fields.UNDERSCORE_ID, "$tender._id");
    project.put("tenderWithAwards", new BasicDBObject("$cond", Arrays.asList(new BasicDBObject("$eq",
            Arrays.asList(ref(MongoConstants.FieldNames.AWARDS_STATUS), Award.Status.active.toString())), 1,
            0)));/*w  w w. ja v  a 2s.  c  om*/
    project.put("tenderWithAwardsValue",
            new BasicDBObject("$cond",
                    Arrays.asList(
                            new BasicDBObject("$eq",
                                    Arrays.asList(ref(MongoConstants.FieldNames.AWARDS_STATUS),
                                            Award.Status.active.toString())),
                            ref(MongoConstants.FieldNames.TENDER_VALUE_AMOUNT), 0)));
    project.putAll(filterProjectMap);

    DBObject group1 = new BasicDBObject();
    group1.put(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF);
    addYearlyMonthlyGroupingOperationFirst(filter, group1);
    group1.put("tenderWithAwards", new BasicDBObject("$max", "$tenderWithAwards"));
    group1.put("tenderWithAwardsValue", new BasicDBObject("$max", "$tenderWithAwardsValue"));
    group1.put("tenderAmount", new BasicDBObject("$first", ref(MongoConstants.FieldNames.TENDER_VALUE_AMOUNT)));
    filterProjectMap
            .forEach(
                    (k, v) -> group1
                            .put(k.replace(".", ""),
                                    k.equals("tender.items.classification._id")
                                            ? new BasicDBObject("$first",
                                                    new BasicDBObject("$arrayElemAt",
                                                            Arrays.asList("$" + k, 0)))
                                            : new BasicDBObject("$first", "$" + k)));

    Aggregation agg = Aggregation
            .newAggregation(
                    match(where(MongoConstants.FieldNames.TENDER_STATUS)
                            .is(Tender.Status.active.toString())
                            .and(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE).exists(true)
                            .andOperator(getYearDefaultFilterCriteria(filter,
                                    MongoConstants.FieldNames.TENDER_PERIOD_START_DATE))),
                    getMatchDefaultFilterOperation(filter), new CustomUnwindOperation("$awards", true),
                    new CustomProjectionOperation(project), new CustomGroupingOperation(group1),
                    getTopXFilterOperation(filter, getYearlyMonthlyGroupingFields(filter))
                            .sum("tenderWithAwardsValue").as(Keys.TOTAL_TENDER_AMOUNT).count()
                            .as(Keys.TOTAL_TENDERS).sum("tenderWithAwards").as(Keys.TOTAL_TENDER_WITH_AWARDS),
                    project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS)
                            .andInclude(
                                    Fields.from(Fields.field(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF)))
                            .and(Keys.TOTAL_TENDER_WITH_AWARDS).divide(Keys.TOTAL_TENDERS)
                            .as(Keys.FRACTION_TENDERS_WITH_AWARDS),
                    project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS,
                            Fields.UNDERSCORE_ID).and(Keys.FRACTION_TENDERS_WITH_AWARDS).multiply(100)
                                    .as(Keys.PERCENTAGE_TENDERS_WITH_AWARDS),
                    (filter.getGroupByCategory() == null ? transformYearlyGrouping(filter) : project())
                            .andInclude(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS,
                                    Keys.TOTAL_TENDER_WITH_AWARDS, Keys.PERCENTAGE_TENDERS_WITH_AWARDS),
                    filter.getGroupByCategory() == null ? getSortByYearMonth(filter)
                            : sort(Sort.Direction.DESC, Keys.TOTAL_TENDER_AMOUNT),
                    skip(filter.getSkip()), limit(filter.getPageSize()))
            .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());

    return releaseAgg(agg);
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "Number of procurements by tender status for a list of procuring entities")
@RequestMapping(value = "/api/procurementsByTenderStatus", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> procurementsByTenderStatus(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(// w  ww.ja va  2 s . co m
            match(where(MongoConstants.FieldNames.TENDER_STATUS).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID),
                    Fields.field("procuringEntityName", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_NAME),
                    Fields.field("tenderStatus", MongoConstants.FieldNames.TENDER_STATUS))).count()
                            .as("count"));

    return releaseAgg(agg);
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "Number of procurements by procurement method for a list of procuring entities")
@RequestMapping(value = "/api/procurementsByProcurementMethod", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> procurementsByProcurementMethod(
        @ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(//from   w  w w.  j  a v a 2  s.c  om
            match(where(MongoConstants.FieldNames.TENDER_PROC_METHOD).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID),
                    Fields.field("procuringEntityName", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_NAME),
                    Fields.field("tenderStatus", MongoConstants.FieldNames.TENDER_PROC_METHOD))).count()
                            .as("count"));

    return releaseAgg(agg);
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "List of buyers with releases for the given procuring entities."
        + "procuringEntityId is mandatory")
@RequestMapping(value = "/api/buyersForProcuringEntities", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> buyersProcuringEntities(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(/*w  ww  .ja  v a2 s  .  c  o  m*/
            match(where(MongoConstants.FieldNames.BUYER_ID).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(Fields.field("buyerId", MongoConstants.FieldNames.BUYER_ID),
                    Fields.field("buyerName", MongoConstants.FieldNames.BUYER_NAME),
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID))));

    return releaseAgg(agg);
}