Example usage for com.mongodb QueryBuilder QueryBuilder

List of usage examples for com.mongodb QueryBuilder QueryBuilder

Introduction

In this page you can find the example usage for com.mongodb QueryBuilder QueryBuilder.

Prototype

public QueryBuilder() 

Source Link

Document

Creates a builder with an empty query

Usage

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult deleteStudy(String studyName, QueryOptions options) {
    if (options == null) {
        options = new QueryOptions();
    }//from ww  w .j a v  a 2 s .  co  m
    StudyConfiguration studyConfiguration = studyConfigurationManager.getStudyConfiguration(studyName, options)
            .first();
    DBObject query = parseQuery(new Query(VariantQueryParams.STUDIES.key(), studyConfiguration.getStudyId()),
            new QueryBuilder()).get();

    // { $pull : { files : {  sid : <studyId> } } }
    BasicDBObject update = new BasicDBObject("$pull",
            new BasicDBObject(DBObjectToVariantConverter.STUDIES_FIELD, new BasicDBObject(
                    DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, studyConfiguration.getStudyId())));
    QueryResult<WriteResult> result = variantsCollection.update(query, update, new QueryOptions("multi", true));

    logger.debug("deleteStudy: query = {}", query);
    logger.debug("deleteStudy: update = {}", update);

    if (options.getBoolean("purge", false)) {
        BasicDBObject purgeQuery = new BasicDBObject(DBObjectToVariantConverter.STUDIES_FIELD,
                new BasicDBObject("$size", 0));
        variantsCollection.remove(purgeQuery, new QueryOptions("multi", true));
    }

    return result;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getFrequency(Query query, Region region, int regionIntervalSize) {
    // db.variants.aggregate( { $match: { $and: [ {chr: "1"}, {start: {$gt: 251391, $lt: 2701391}} ] }},
    //                        { $group: { _id: { $subtract: [ { $divide: ["$start", 20000] }, { $divide: [{$mod: ["$start", 20000]}, 20000] } ] },
    //                                  totalCount: {$sum: 1}}})

    QueryOptions options = new QueryOptions();

    // If interval is not provided is set to the value that returns 200 values
    if (regionIntervalSize <= 0) {
        //            regionIntervalSize = options.getInt("interval", (region.getEnd() - region.getStart()) / 200);
        regionIntervalSize = (region.getEnd() - region.getStart()) / 200;
    }// w w w.ja  va  2s  .  com

    BasicDBObject start = new BasicDBObject("$gt", region.getStart());
    start.append("$lt", region.getEnd());

    BasicDBList andArr = new BasicDBList();
    andArr.add(new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, region.getChromosome()));
    andArr.add(new BasicDBObject(DBObjectToVariantConverter.START_FIELD, start));

    // Parsing the rest of options
    QueryBuilder qb = new QueryBuilder();
    //        DBObject optionsMatch = parseQueryOptions(options, qb).get();
    DBObject optionsMatch = parseQuery(query, qb).get();
    if (!optionsMatch.keySet().isEmpty()) {
        andArr.add(optionsMatch);
    }
    DBObject match = new BasicDBObject("$match", new BasicDBObject("$and", andArr));

    //        qb.and("_at.chunkIds").in(chunkIds);
    //        qb.and(DBObjectToVariantConverter.END_FIELD).greaterThanEquals(region.getStart());
    //        qb.and(DBObjectToVariantConverter.START_FIELD).lessThanEquals(region.getEnd());
    //
    //        List<String> chunkIds = getChunkIds(region);
    //        DBObject regionObject = new BasicDBObject("_at.chunkIds", new BasicDBObject("$in", chunkIds))
    //                .append(DBObjectToVariantConverter.END_FIELD, new BasicDBObject("$gte", region.getStart()))
    //                .append(DBObjectToVariantConverter.START_FIELD, new BasicDBObject("$lte", region.getEnd()));

    BasicDBList divide1 = new BasicDBList();
    divide1.add("$start");
    divide1.add(regionIntervalSize);

    BasicDBList divide2 = new BasicDBList();
    divide2.add(new BasicDBObject("$mod", divide1));
    divide2.add(regionIntervalSize);

    BasicDBList subtractList = new BasicDBList();
    subtractList.add(new BasicDBObject("$divide", divide1));
    subtractList.add(new BasicDBObject("$divide", divide2));

    BasicDBObject subtract = new BasicDBObject("$subtract", subtractList);
    DBObject totalCount = new BasicDBObject("$sum", 1);
    BasicDBObject g = new BasicDBObject("_id", subtract);
    g.append("features_count", totalCount);
    DBObject group = new BasicDBObject("$group", g);
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));

    //        logger.info("getAllIntervalFrequencies - (>_)>");
    //        System.out.println(options.toString());
    //        System.out.println(match.toString());
    //        System.out.println(group.toString());
    //        System.out.println(sort.toString());

    long dbTimeStart = System.currentTimeMillis();
    QueryResult output = variantsCollection.aggregate(/*"$histogram", */Arrays.asList(match, group, sort),
            options);
    long dbTimeEnd = System.currentTimeMillis();

    Map<Long, DBObject> ids = new HashMap<>();
    // Create DBObject for intervals with features inside them
    for (DBObject intervalObj : (List<DBObject>) output.getResult()) {
        Long _id = Math.round((Double) intervalObj.get("_id"));//is double

        DBObject intervalVisited = ids.get(_id);
        if (intervalVisited == null) {
            intervalObj.put("_id", _id);
            intervalObj.put("start", getChunkStart(_id.intValue(), regionIntervalSize));
            intervalObj.put("end", getChunkEnd(_id.intValue(), regionIntervalSize));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", Math.log((int) intervalObj.get("features_count")));
            ids.put(_id, intervalObj);
        } else {
            Double sum = (Double) intervalVisited.get("features_count")
                    + Math.log((int) intervalObj.get("features_count"));
            intervalVisited.put("features_count", sum.intValue());
        }
    }

    // Create DBObject for intervals without features inside them
    BasicDBList resultList = new BasicDBList();
    int firstChunkId = getChunkId(region.getStart(), regionIntervalSize);
    int lastChunkId = getChunkId(region.getEnd(), regionIntervalSize);
    DBObject intervalObj;
    for (int chunkId = firstChunkId; chunkId <= lastChunkId; chunkId++) {
        intervalObj = ids.get((long) chunkId);
        if (intervalObj == null) {
            intervalObj = new BasicDBObject();
            intervalObj.put("_id", chunkId);
            intervalObj.put("start", getChunkStart(chunkId, regionIntervalSize));
            intervalObj.put("end", getChunkEnd(chunkId, regionIntervalSize));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", 0);
        }
        resultList.add(intervalObj);
    }

    QueryResult queryResult = new QueryResult(region.toString(), ((Long) (dbTimeEnd - dbTimeStart)).intValue(),
            resultList.size(), resultList.size(), null, null, resultList);

    return queryResult;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult deleteAnnotation(String annotationId, Query query, QueryOptions queryOptions) {
    if (queryOptions == null) {
        queryOptions = new QueryOptions();
    }/*  w ww.ja  v a  2s.  com*/
    //        queryOptions.put(VariantQueryParams.STUDIES.key(), studyId);
    DBObject dbQuery = parseQuery(query, new QueryBuilder()).get();

    //        DBObject update = new BasicDBObject("$unset", new BasicDBObject(DBObjectToVariantConverter.ANNOTATION_FIELD, ""));
    DBObject update = new BasicDBObject("$set",
            new BasicDBObject(DBObjectToVariantConverter.ANNOTATION_FIELD + ".0", null));

    logger.debug("deleteAnnotation: query = {}", dbQuery);
    logger.debug("deleteAnnotation: update = {}", update);

    return variantsCollection.update(dbQuery, update, new QueryOptions("multi", true));
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

private QueryBuilder addScoreFilter(String key, List<String> list, QueryBuilder builder) {
    List<DBObject> ands = new ArrayList<>();
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        String elem = iterator.next();
        String[] populationFrequency = splitKeyValue(elem);
        QueryBuilder scoreBuilder = new QueryBuilder();
        scoreBuilder.and(DBObjectToVariantAnnotationConverter.SCORE_SOURCE_FIELD).is(populationFrequency[0]);
        addCompQueryFilter(DBObjectToVariantAnnotationConverter.SCORE_SCORE_FIELD, populationFrequency[1],
                scoreBuilder);// www .  j  av  a  2 s  . co  m
        ands.add(new BasicDBObject(key, new BasicDBObject("$elemMatch", scoreBuilder.get())));
    }
    if (!ands.isEmpty()) {
        builder.and(ands.toArray(new DBObject[ands.size()]));
    }
    return builder;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

private QueryBuilder addFrequencyFilter(String key, String alleleFrequencyField, List<String> list,
        QueryBuilder builder) {// ww  w.  j a  va  2 s . c o m
    List<DBObject> ands = new ArrayList<>();
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        String elem = iterator.next();
        String[] split = elem.split(":");
        if (split.length == 2) {
            String study = split[0];
            String population = split[1];
            //                String frequency = split[2];
            String[] populationFrequency = splitKeyValue(population);
            QueryBuilder frequencyBuilder = new QueryBuilder();
            frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_STUDY_FIELD)
                    .is(study);
            //                frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_POP_FIELD).is(population);
            frequencyBuilder.and(DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_POP_FIELD)
                    .is(populationFrequency[0]);
            //                addCompQueryFilter(alleleFrequencyField, frequency, frequencyBuilder);
            System.out.println("populationFrequency = " + Arrays.toString(populationFrequency));
            addCompQueryFilter(alleleFrequencyField, populationFrequency[1], frequencyBuilder);
            ands.add(new BasicDBObject(key, new BasicDBObject("$elemMatch", frequencyBuilder.get())));
        } else {
            logger.error("Bad score filter: " + elem);
            iterator.remove(); //Remove the malformed query params.
        }
    }
    if (!ands.isEmpty()) {
        builder.and(ands.toArray(new DBObject[ands.size()]));
    }
    return builder;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Override
@Deprecated//  w  w  w .  j ava2  s .c o  m
public QueryResult getVariantFrequencyByRegion(Region region, QueryOptions options) {
    // db.variants.aggregate( { $match: { $and: [ {chr: "1"}, {start: {$gt: 251391, $lt: 2701391}} ] }}, 
    //                        { $group: { _id: { $subtract: [ { $divide: ["$start", 20000] }, { $divide: [{$mod: ["$start", 20000]}, 20000] } ] }, 
    //                                  totalCount: {$sum: 1}}})

    if (options == null) {
        options = new QueryOptions();
    }

    int interval = options.getInt("interval", 20000);

    BasicDBObject start = new BasicDBObject("$gt", region.getStart());
    start.append("$lt", region.getEnd());

    BasicDBList andArr = new BasicDBList();
    andArr.add(new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, region.getChromosome()));
    andArr.add(new BasicDBObject(DBObjectToVariantConverter.START_FIELD, start));

    // Parsing the rest of options
    QueryBuilder qb = new QueryBuilder();
    DBObject optionsMatch = parseQueryOptions(options, qb).get();
    if (!optionsMatch.keySet().isEmpty()) {
        andArr.add(optionsMatch);
    }
    DBObject match = new BasicDBObject("$match", new BasicDBObject("$and", andArr));

    //        qb.and("_at.chunkIds").in(chunkIds);
    //        qb.and(DBObjectToVariantConverter.END_FIELD).greaterThanEquals(region.getStart());
    //        qb.and(DBObjectToVariantConverter.START_FIELD).lessThanEquals(region.getEnd());
    //
    //        List<String> chunkIds = getChunkIds(region);
    //        DBObject regionObject = new BasicDBObject("_at.chunkIds", new BasicDBObject("$in", chunkIds))
    //                .append(DBObjectToVariantConverter.END_FIELD, new BasicDBObject("$gte", region.getStart()))
    //                .append(DBObjectToVariantConverter.START_FIELD, new BasicDBObject("$lte", region.getEnd()));

    BasicDBList divide1 = new BasicDBList();
    divide1.add("$start");
    divide1.add(interval);

    BasicDBList divide2 = new BasicDBList();
    divide2.add(new BasicDBObject("$mod", divide1));
    divide2.add(interval);

    BasicDBList subtractList = new BasicDBList();
    subtractList.add(new BasicDBObject("$divide", divide1));
    subtractList.add(new BasicDBObject("$divide", divide2));

    BasicDBObject substract = new BasicDBObject("$subtract", subtractList);

    DBObject totalCount = new BasicDBObject("$sum", 1);

    BasicDBObject g = new BasicDBObject("_id", substract);
    g.append("features_count", totalCount);
    DBObject group = new BasicDBObject("$group", g);

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));

    //        logger.info("getAllIntervalFrequencies - (>_)>");
    //        System.out.println(options.toString());
    //
    //        System.out.println(match.toString());
    //        System.out.println(group.toString());
    //        System.out.println(sort.toString());

    long dbTimeStart = System.currentTimeMillis();
    QueryResult output = variantsCollection.aggregate(/*"$histogram", */Arrays.asList(match, group, sort),
            options);
    long dbTimeEnd = System.currentTimeMillis();

    Map<Long, DBObject> ids = new HashMap<>();
    // Create DBObject for intervals with features inside them
    for (DBObject intervalObj : (List<DBObject>) output.getResult()) {
        Long _id = Math.round((Double) intervalObj.get("_id"));//is double

        DBObject intervalVisited = ids.get(_id);
        if (intervalVisited == null) {
            intervalObj.put("_id", _id);
            intervalObj.put("start", getChunkStart(_id.intValue(), interval));
            intervalObj.put("end", getChunkEnd(_id.intValue(), interval));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", Math.log((int) intervalObj.get("features_count")));
            ids.put(_id, intervalObj);
        } else {
            Double sum = (Double) intervalVisited.get("features_count")
                    + Math.log((int) intervalObj.get("features_count"));
            intervalVisited.put("features_count", sum.intValue());
        }
    }

    // Create DBObject for intervals without features inside them
    BasicDBList resultList = new BasicDBList();
    int firstChunkId = getChunkId(region.getStart(), interval);
    int lastChunkId = getChunkId(region.getEnd(), interval);
    DBObject intervalObj;
    for (int chunkId = firstChunkId; chunkId <= lastChunkId; chunkId++) {
        intervalObj = ids.get((long) chunkId);
        if (intervalObj == null) {
            intervalObj = new BasicDBObject();
            intervalObj.put("_id", chunkId);
            intervalObj.put("start", getChunkStart(chunkId, interval));
            intervalObj.put("end", getChunkEnd(chunkId, interval));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", 0);
        }
        resultList.add(intervalObj);
    }

    QueryResult queryResult = new QueryResult(region.toString(), ((Long) (dbTimeEnd - dbTimeStart)).intValue(),
            resultList.size(), resultList.size(), null, null, resultList);

    return queryResult;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Deprecated
public QueryResult deleteStudy(int studyId, QueryOptions queryOptions) {

    if (queryOptions == null) {
        queryOptions = new QueryOptions();
    }//w  ww  . j av  a2s. co m
    queryOptions.put(VariantQueryParams.STUDIES.key(), studyId);
    DBObject query = parseQueryOptions(queryOptions, new QueryBuilder()).get();

    // { $pull : { files : {  sid : <studyId> } } }
    BasicDBObject update = new BasicDBObject("$pull",
            new BasicDBObject(DBObjectToVariantConverter.STUDIES_FIELD,
                    new BasicDBObject(DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, studyId)));
    QueryResult<WriteResult> result = variantsCollection.update(query, update, new QueryOptions("multi", true));

    logger.debug("deleteStudy: query = {}", query);
    logger.debug("deleteStudy: update = {}", update);

    if (queryOptions.getBoolean("purge", false)) {
        BasicDBObject purgeQuery = new BasicDBObject(DBObjectToVariantConverter.STUDIES_FIELD,
                new BasicDBObject("$size", 0));
        variantsCollection.remove(purgeQuery, new QueryOptions("multi", true));
    }

    return result;
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

License:Apache License

@Deprecated
QueryResult deleteAnnotation(int annotationId, int studyId, QueryOptions queryOptions) {

    if (queryOptions == null) {
        queryOptions = new QueryOptions();
    }/*from  w w  w . j  a  v  a 2  s . c  o  m*/
    queryOptions.put(VariantQueryParams.STUDIES.key(), studyId);
    DBObject query = parseQueryOptions(queryOptions, new QueryBuilder()).get();

    DBObject update = new BasicDBObject("$unset",
            new BasicDBObject(DBObjectToVariantConverter.ANNOTATION_FIELD, ""));

    logger.debug("deleteAnnotation: query = {}", query);
    logger.debug("deleteAnnotation: update = {}", update);

    return variantsCollection.update(query, update, new QueryOptions("multi", true));
}

From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java

License:Apache License

private DBObject createMongoQuery(final SearchCriteria searchCriteria) {

    QueryBuilder queryBuilder = null;// ww  w .j  a  v  a  2 s  . co m

    final List<SearchCriterion> and = searchCriteria.getAnd();
    if (and != null && !and.isEmpty()) {

        queryBuilder = new QueryBuilder();

        for (final SearchCriterion searchCriterion : and) {

            final String referenceSlot = searchCriterion.getReferenceSlot();
            queryBuilder.and(referenceSlot);
            addQueryCriterion(searchCriterion, queryBuilder);

        }

    }

    final List<SearchCriterion> or = searchCriteria.getOr();
    if (or != null && !or.isEmpty()) {

        final DBObject[] orQueryCriterionArray = new DBObject[or.size()];
        for (int i = 0; i < or.size(); i++) {
            final SearchCriterion searchCriterion = or.get(i);
            final String referenceSlot = searchCriterion.getReferenceSlot();
            final QueryBuilder orQueryCriterionBuilder = QueryBuilder.start(referenceSlot);
            addQueryCriterion(searchCriterion, orQueryCriterionBuilder);
            orQueryCriterionArray[i] = orQueryCriterionBuilder.get();
        }

        final QueryBuilder orQueryBuilder = new QueryBuilder();
        orQueryBuilder.or(orQueryCriterionArray);

        if (queryBuilder != null) {
            // AND the OR clause together with the AND query
            queryBuilder.and(orQueryBuilder.get());
        } else {
            queryBuilder = orQueryBuilder;
        }
    }

    if (queryBuilder == null) {
        return null;
    }

    final DBObject mongoQuery = queryBuilder.get();
    return mongoQuery;
}