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.cellbase.mongodb.db.network.ProteinProteinInteractionMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getAll(QueryOptions options) {
    QueryBuilder builder = new QueryBuilder();

    // Fiilter all by interactor ID
    List<Object> interactors = options.getList("interactor", null);
    if (interactors != null && interactors.size() > 0) {
        BasicDBList interactorDBList = new BasicDBList();
        interactorDBList.addAll(interactors);

        BasicDBList or = new BasicDBList();
        DBObject orA = new BasicDBObject("interactorA.xrefs.id", new BasicDBObject("$in", interactorDBList));
        DBObject orB = new BasicDBObject("interactorB.xrefs.id", new BasicDBObject("$in", interactorDBList));
        or.add(orA);//from   ww w  .j  a v a 2  s . c o  m
        or.add(orB);
        //            builder = builder.or(orA, orB);
        builder = builder.and(new BasicDBObject("$or", or));
    }

    // Filter all by Interaction Type (name and PSIMI)
    List<Object> type = options.getList("type", null);
    if (type != null && type.size() > 0) {
        BasicDBList typeDBList = new BasicDBList();
        typeDBList.addAll(type);

        BasicDBList or = new BasicDBList();
        DBObject orName = new BasicDBObject("type.name", new BasicDBObject("$in", typeDBList));
        DBObject orPsimi = new BasicDBObject("type.psimi", new BasicDBObject("$in", typeDBList));
        or.add(orName);
        or.add(orPsimi);
        //            builder = builder.or(orName, orPsimi);
        builder = builder.and(new BasicDBObject("$or", or));
    }

    // Filter all by source database
    List<Object> database = options.getList("database", null);
    if (database != null && database.size() > 0) {
        BasicDBList databaseDBList = new BasicDBList();
        databaseDBList.addAll(database);
        builder = builder.and("source.name").in(databaseDBList);
    }

    // Filter all by detection method (name and PSIMI)
    List<Object> detectionMethod = options.getList("detectionMethod", null);
    if (detectionMethod != null && detectionMethod.size() > 0) {
        BasicDBList detectionMethodDBList = new BasicDBList();
        detectionMethodDBList.addAll(detectionMethod);

        BasicDBList or = new BasicDBList();
        DBObject orName = new BasicDBObject("detectionMethod.name",
                new BasicDBObject("$in", detectionMethodDBList));
        DBObject orPsimi = new BasicDBObject("detectionMethod.psimi",
                new BasicDBObject("$in", detectionMethodDBList));
        or.add(orName);
        or.add(orPsimi);
        //            builder = builder.or(orName, orPsimi);
        builder = builder.and(new BasicDBObject("$or", or));
    }

    // Filter all by status
    List<Object> status = options.getList("status", null);
    if (status != null && status.size() > 0) {
        BasicDBList statusDBList = new BasicDBList();
        statusDBList.addAll(status);
        builder = builder.and("status").in(statusDBList);
    }

    //        List<Object> type = options.getList("type", null);
    //        if (type != null && type.size() > 0) {
    //            BasicDBList typeDBList = new BasicDBList();
    //            typeDBList.addAll(type);
    //            builder = builder.and("type.name").in(typeDBList);
    //        }

    //        String type = options.getString("type", null);
    //        if (type != null && !type.equals("")) {
    //            builder = builder.and("type.name").is(type);
    //        }

    System.out.println(builder.get().toString());
    //      options = addExcludeReturnFields("transcripts", options);
    return executeQuery("result", builder.get(), options);
}

From source file:org.opencb.cellbase.mongodb.db.regulatory.RegulatoryRegionMongoDBAdaptor.java

License:Apache License

@Override
public List<QueryResult> getAllByRegionList(List<Region> regionList, QueryOptions options) {
    //  db.regulatory_region.find({"chunkIds": {$in:["1_200", "1_300"]}, "start": 601156})
    QueryBuilder builder = new QueryBuilder();

    List<Object> featureType = options.getAsList("featureType");
    List<Object> featureClass = options.getAsList("featureClass");

    //        options = addExcludeReturnFields("chunkIds", options);

    List<DBObject> queries = new ArrayList<>();
    for (Region region : regionList) {
        int firstChunkId = getChunkId(region.getStart(), regulatoryRegionChunkSize);
        int lastChunkId = getChunkId(region.getEnd(), regulatoryRegionChunkSize);
        BasicDBList chunksId = new BasicDBList();
        for (int j = firstChunkId; j <= lastChunkId; j++) {
            String chunkId = region.getChromosome() + "_" + j + "_" + regulatoryRegionChunkSize / 1000 + "k";
            chunksId.add(chunkId);/*from   ww w .  ja  va 2 s . c  o  m*/
        }

        //            logger.info(chunksId.toString());

        builder = builder.start("_chunkIds").in(chunksId).and("start").lessThanEquals(region.getEnd())
                .and("end").greaterThanEquals(region.getStart());

        if (featureType != null && featureType.size() > 0) {
            BasicDBList featureTypeDBList = new BasicDBList();
            featureTypeDBList.addAll(featureType);
            builder = builder.and("featureType").in(featureTypeDBList);
        }

        if (featureClass != null && featureClass.size() > 0) {
            BasicDBList featureClassDBList = new BasicDBList();
            featureClassDBList.addAll(featureClass);
            builder = builder.and("featureClass").in(featureClassDBList);
        }

        queries.add(builder.get());
    }
    //        System.out.println(">>"+regionList);
    //        System.out.println(">>"+builder.get().toString());
    return executeQueryList2(regionList, queries, options);
}

From source file:org.opencb.cellbase.mongodb.db.TranscriptMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getAll(QueryOptions options) {
    QueryBuilder builder = new QueryBuilder();

    DBObject[] commands = new DBObject[2];
    DBObject unwind = new BasicDBObject("$unwind", "$transcripts");
    commands[0] = unwind;//from www .  jav a 2  s  .  c  o  m

    List<Object> biotypes = options.getList("biotypes", null);
    if (biotypes != null && biotypes.size() > 0) {

        //            DBObject match = new BasicDBObject("$match", new BasicDBObject("chunkIds", id));
        //            builder = builder.and("biotype").in(biotypeIds);

        //            commands[0] = match;
        commands[1] = unwind;
    } else {
        commands[0] = unwind;
    }

    //      options = addExcludeReturnFields("transcripts", options);
    return executeAggregation("result", commands, options);
}

From source file:org.opencb.cellbase.mongodb.db.variation.VariationMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getAllPhenotypes(QueryOptions options) {
    //        return executeDistinct("distinct", "phenotype", mongoVariationPhenotypeDBCollection);
    QueryBuilder builder = new QueryBuilder();
    if (options.containsKey("phenotype")) {
        String pheno = options.getString("phenotype");
        if (pheno != null && !pheno.equals("")) {
            builder = builder.start("phenotype").is(pheno);
        }//  w ww  . j  ava 2 s  .  c  om
    }
    return executeQuery("result", builder.get(), options);
    //        return executeQuery("result", builder.get(), options, mongoVariationPhenotypeDBCollection);
}

From source file:org.opencb.cellbase.mongodb.db.VariationMongoDBAdaptor.java

License:Apache License

@Override
public QueryResult getAllPhenotypes(QueryOptions options) {
    //        return executeDistinct("distinct", "phenotype", mongoVariationPhenotypeDBCollection);
    QueryBuilder builder = new QueryBuilder();
    if (options.containsKey("phenotype")) {
        String pheno = options.getString("phenotype");
        if (pheno != null && !pheno.equals("")) {
            builder = builder.start("phenotype").is(pheno);
        }//from   ww  w . ja v  a  2s. co  m
    }
    return executeQuery("result", builder.get(), options, mongoVariationPhenotypeDBCollection);
}

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

License:Apache License

private Document parseQuery(final Query originalQuery) {
    QueryBuilder builder = new QueryBuilder();
    if (originalQuery != null) {
        // Copy given query. It may be modified
        Query query = new Query(originalQuery);
        boolean nonGeneRegionFilter = false;
        /* VARIANT PARAMS */
        List<Region> regions = new ArrayList<>();
        if (isValidParam(query, VariantQueryParams.CHROMOSOME)) {
            nonGeneRegionFilter = true;//from  w w  w. j  a va 2 s  .com
            regions.addAll(Region.parseRegions(query.getString(VariantQueryParams.CHROMOSOME.key()), true));
        }

        if (isValidParam(query, VariantQueryParams.REGION)) {
            nonGeneRegionFilter = true;
            regions.addAll(Region.parseRegions(query.getString(VariantQueryParams.REGION.key()), true));
        }
        if (!regions.isEmpty()) {
            getRegionFilter(regions, builder);
        }

        // List with all MongoIds from ID and XREF filters
        List<String> mongoIds = new ArrayList<>();

        if (isValidParam(query, VariantQueryParams.ID)) {
            nonGeneRegionFilter = true;
            List<String> idsList = query.getAsStringList(VariantQueryParams.ID.key());
            List<String> otherIds = new ArrayList<>(idsList.size());

            for (String value : idsList) {
                Variant variant = toVariant(value);
                if (variant != null) {
                    mongoIds.add(MongoDBVariantStageLoader.STRING_ID_CONVERTER.buildId(variant));
                } else {
                    otherIds.add(value);
                }
            }

            if (!otherIds.isEmpty()) {
                String ids = otherIds.stream().collect(Collectors.joining(","));
                addQueryStringFilter(
                        DocumentToVariantConverter.ANNOTATION_FIELD + "."
                                + DocumentToVariantAnnotationConverter.XREFS_FIELD + "."
                                + DocumentToVariantAnnotationConverter.XREF_ID_FIELD,
                        ids, builder, QueryOperation.OR);
                addQueryStringFilter(DocumentToVariantConverter.IDS_FIELD, ids, builder, QueryOperation.OR);
            }
        }

        List<String> genes = new ArrayList<>(query.getAsStringList(VariantQueryParams.GENE.key()));

        if (isValidParam(query, VariantQueryParams.ANNOT_XREF)) {
            List<String> xrefs = query.getAsStringList(VariantQueryParams.ANNOT_XREF.key());
            List<String> otherXrefs = new ArrayList<>();
            for (String value : xrefs) {
                Variant variant = toVariant(value);
                if (variant != null) {
                    mongoIds.add(MongoDBVariantStageLoader.STRING_ID_CONVERTER.buildId(variant));
                } else {
                    if (isVariantAccession(value) || isClinicalAccession(value) || isGeneAccession(value)) {
                        otherXrefs.add(value);
                    } else {
                        genes.add(value);
                    }
                }
            }

            if (!otherXrefs.isEmpty()) {
                nonGeneRegionFilter = true;
                addQueryStringFilter(
                        DocumentToVariantConverter.ANNOTATION_FIELD + '.'
                                + DocumentToVariantAnnotationConverter.XREFS_FIELD + '.'
                                + DocumentToVariantAnnotationConverter.XREF_ID_FIELD,
                        String.join(",", otherXrefs), builder, QueryOperation.OR);
            }
        }

        if (!genes.isEmpty()) {
            if (isValidParam(query, VariantQueryParams.ANNOT_CONSEQUENCE_TYPE)) {
                List<String> soList = query.getAsStringList(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key());
                Set<String> gnSo = new HashSet<>(genes.size() * soList.size());
                for (String gene : genes) {
                    for (String so : soList) {
                        int soNumber = parseConsequenceType(so);
                        gnSo.add(DocumentToVariantAnnotationConverter.buildGeneSO(gene, soNumber));
                    }
                }
                builder.or(new BasicDBObject(
                        DocumentToVariantConverter.ANNOTATION_FIELD + '.'
                                + DocumentToVariantAnnotationConverter.GENE_SO_FIELD,
                        new BasicDBObject("$in", gnSo)));
                if (!nonGeneRegionFilter) {
                    // Filter already present in the GENE_SO_FIELD
                    query.remove(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key());
                }
            } else {
                addQueryStringFilter(
                        DocumentToVariantConverter.ANNOTATION_FIELD + '.'
                                + DocumentToVariantAnnotationConverter.XREFS_FIELD + '.'
                                + DocumentToVariantAnnotationConverter.XREF_ID_FIELD,
                        String.join(",", genes), builder, QueryOperation.OR);
            }
        }

        if (!mongoIds.isEmpty()) {
            if (mongoIds.size() == 1) {
                builder.or(new QueryBuilder().and("_id").is(mongoIds.get(0)).get());
            } else {
                builder.or(new QueryBuilder().and("_id").in(mongoIds).get());
            }
        }

        if (isValidParam(query, VariantQueryParams.REFERENCE)) {
            addQueryStringFilter(DocumentToVariantConverter.REFERENCE_FIELD,
                    query.getString(VariantQueryParams.REFERENCE.key()), builder, QueryOperation.AND);
        }

        if (isValidParam(query, VariantQueryParams.ALTERNATE)) {
            addQueryStringFilter(DocumentToVariantConverter.ALTERNATE_FIELD,
                    query.getString(VariantQueryParams.ALTERNATE.key()), builder, QueryOperation.AND);
        }

        if (isValidParam(query, VariantQueryParams.TYPE)) {
            addQueryFilter(DocumentToVariantConverter.TYPE_FIELD,
                    query.getString(VariantQueryParams.TYPE.key()), builder, QueryOperation.AND, s -> {
                        Set<VariantType> subTypes = Variant.subTypes(VariantType.valueOf(s));
                        List<String> types = new ArrayList<>(subTypes.size() + 1);
                        types.add(s);
                        subTypes.forEach(subType -> types.add(subType.toString()));
                        return types;
                    }); //addQueryStringFilter(DBObjectToVariantConverter.TYPE_FIELD,
            //                query.getString(VariantQueryParams.TYPE.key()), builder, QueryOperation.AND);
        }

        /* ANNOTATION PARAMS */
        parseAnnotationQueryParams(query, builder);

        /* STUDIES */
        final StudyConfiguration defaultStudyConfiguration = parseStudyQueryParams(query, builder);

        /* STATS PARAMS */
        parseStatsQueryParams(query, builder, defaultStudyConfiguration);
    }
    logger.debug("Query         = {}", originalQuery == null ? "{}" : originalQuery.toJson());
    Document mongoQuery = new Document(builder.get().toMap());
    logger.debug("MongoDB Query = {}", mongoQuery.toJson(new JsonWriterSettings(JsonMode.SHELL, false)));
    return mongoQuery;
}

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

License:Apache License

/**
 * Accepts a list of filters separated with "," or ";" with the expression: {SOURCE}{OPERATION}{VALUE}.
 *
 * @param value         Value to parse//from   w  w  w  . j ava 2  s.  c o  m
 * @param builder       QueryBuilder
 * @param scoreParam    Score VariantQueryParam
 * @param defaultSource Default source value. If null, must be present in the filter. If not, must not be present.
 * @param allowDescriptionFilter Use string values as filters for the score description
 * @return QueryBuilder
 */
private QueryBuilder addScoreFilter(String value, QueryBuilder builder, VariantQueryParams scoreParam,
        final String defaultSource, boolean allowDescriptionFilter) {
    final List<String> list;
    QueryOperation operation = checkOperator(value);
    list = splitValue(value, operation);
    List<DBObject> dbObjects = new ArrayList<>();
    for (String elem : list) {
        String[] score = VariantDBAdaptorUtils.splitOperator(elem);
        String source;
        String op;
        String scoreValue;
        // No given score
        if (StringUtils.isEmpty(score[0])) {
            if (defaultSource == null) {
                logger.error("Bad score filter: " + elem);
                throw VariantQueryException.malformedParam(scoreParam, value);
            }
            source = defaultSource;
            op = score[1];
            scoreValue = score[2];
        } else {
            if (defaultSource != null) {
                logger.error("Bad score filter: " + elem);
                throw VariantQueryException.malformedParam(scoreParam, value);
            }
            source = score[0];
            op = score[1];
            scoreValue = score[2];
        }

        String key = DocumentToVariantAnnotationConverter.SCORE_FIELD_MAP.get(source);
        if (key == null) {
            // Unknown score
            throw VariantQueryException.malformedParam(scoreParam, value);
        }

        QueryBuilder scoreBuilder = new QueryBuilder();
        if (NumberUtils.isParsable(scoreValue)) {
            // Query by score
            key += '.' + DocumentToVariantAnnotationConverter.SCORE_SCORE_FIELD;
            addCompQueryFilter(key, scoreValue, scoreBuilder, op);
        } else if (allowDescriptionFilter) {
            // Query by description
            key += '.' + DocumentToVariantAnnotationConverter.SCORE_DESCRIPTION_FIELD;
            addStringCompQueryFilter(key, scoreValue, scoreBuilder);
        } else {
            throw VariantQueryException.malformedParam(scoreParam, value);
        }
        dbObjects.add(scoreBuilder.get());
    }

    if (!dbObjects.isEmpty()) {
        if (operation == null || operation == QueryOperation.AND) {
            builder.and(dbObjects.toArray(new DBObject[dbObjects.size()]));
        } else {
            builder.and(new BasicDBObject("$or", dbObjects));
        }
    }
    return builder;
}

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

License:Apache License

/**
 * Accepts a list of filters separated with "," or ";" with the expression:
 * {STUDY}:{POPULATION}{OPERATION}{VALUE}.
 *
 * @param key       PopulationFrequency schema field
 * @param value     Value to parse// w w  w .ja  va 2 s  . c om
 * @param builder   QueryBuilder
 * @param addFilter For complex filter
 * @return QueryBuilder
 */
private QueryBuilder addFrequencyFilter(String key, String value, QueryBuilder builder,
        VariantQueryParams queryParam, BiConsumer<String, QueryBuilder> addFilter) {
    final List<String> list;
    QueryOperation operation = checkOperator(value);
    list = splitValue(value, operation);

    List<BasicDBObject> dbObjects = new ArrayList<>();
    for (String elem : list) {
        String[] split = elem.split(IS);
        if (split.length != 2) {
            logger.error("Bad population frequency filter: " + elem);
            throw VariantQueryException.malformedParam(queryParam, value);
            //new IllegalArgumentException("Bad population frequency filter: " + elem);
        }
        String study = split[0];
        String population = split[1];
        String[] populationFrequency = splitKeyValue(population);
        logger.debug("populationFrequency = " + Arrays.toString(populationFrequency));

        QueryBuilder frequencyBuilder = new QueryBuilder();
        frequencyBuilder.and(DocumentToVariantAnnotationConverter.POPULATION_FREQUENCY_STUDY_FIELD).is(study);
        frequencyBuilder.and(DocumentToVariantAnnotationConverter.POPULATION_FREQUENCY_POP_FIELD)
                .is(populationFrequency[0]);
        Document studyPopFilter = new Document(frequencyBuilder.get().toMap());
        addFilter.accept(populationFrequency[1], frequencyBuilder);
        BasicDBObject elemMatch = new BasicDBObject(key,
                new BasicDBObject("$elemMatch", frequencyBuilder.get()));
        if (populationFrequency[1].startsWith("<")) {
            BasicDBObject orNotExistsAnyPopulation = new BasicDBObject(key,
                    new BasicDBObject("$exists", false));
            BasicDBObject orNotExistsPopulation = new BasicDBObject(key,
                    new BasicDBObject("$not", new BasicDBObject("$elemMatch", studyPopFilter)));
            dbObjects.add(new BasicDBObject("$or",
                    Arrays.asList(orNotExistsAnyPopulation, orNotExistsPopulation, elemMatch)));
        } else {
            dbObjects.add(elemMatch);
        }
    }
    if (!dbObjects.isEmpty()) {
        if (operation == null || operation == QueryOperation.AND) {
            builder.and(dbObjects.toArray(new BasicDBObject[dbObjects.size()]));
        } else {
            builder.and(new BasicDBObject("$or", dbObjects));
        }
    }
    return builder;
}

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

License:Apache License

/**
 * Accept filters separated with "," or ";" with the expression:
 * [{STUDY}:]{COHORT}{OPERATION}{VALUE}.
 * Where STUDY is optional if defaultStudyConfiguration is provided
 *
 * @param key                       Stats field to filter
 * @param values                    Values to parse
 * @param builder                   QueryBuilder
 * @param defaultStudyConfiguration/*w  w w.j  a va  2s  . c o m*/
 */
private void addStatsFilterList(String key, String values, QueryBuilder builder,
        StudyConfiguration defaultStudyConfiguration) {
    QueryOperation op = checkOperator(values);
    List<String> valuesList = splitValue(values, op);
    List<DBObject> statsQueries = new LinkedList<>();
    for (String value : valuesList) {
        statsQueries.add(addStatsFilter(key, value, new QueryBuilder(), defaultStudyConfiguration).get());
    }

    if (!statsQueries.isEmpty()) {
        if (op == QueryOperation.OR) {
            builder.or(statsQueries.toArray(new DBObject[statsQueries.size()]));
        } else {
            builder.and(statsQueries.toArray(new DBObject[statsQueries.size()]));
        }
    }
}

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

License:Apache License

/**
 * Accepts filters with the expresion: [{STUDY}:]{COHORT}{OPERATION}{VALUE}.
 * Where STUDY is optional if defaultStudyConfiguration is provided
 *
 * @param key                       Stats field to filter
 * @param filter                    Filter to parse
 * @param builder                   QueryBuilder
 * @param defaultStudyConfiguration/*from  w  w w. j  a  v  a 2s  .com*/
 */
private QueryBuilder addStatsFilter(String key, String filter, QueryBuilder builder,
        StudyConfiguration defaultStudyConfiguration) {
    if (filter.contains(":") || defaultStudyConfiguration != null) {
        Integer studyId;
        Integer cohortId;
        String operator;
        String valueStr;
        if (filter.contains(":")) {
            String[] studyValue = filter.split(":");
            String[] cohortOpValue = VariantDBAdaptorUtils.splitOperator(studyValue[1]);
            String study = studyValue[0];
            String cohort = cohortOpValue[0];
            operator = cohortOpValue[1];
            valueStr = cohortOpValue[2];

            StudyConfiguration studyConfiguration = utils.getStudyConfiguration(study,
                    defaultStudyConfiguration);
            cohortId = utils.getCohortId(cohort, studyConfiguration);
            studyId = studyConfiguration.getStudyId();
        } else {
            //                String study = defaultStudyConfiguration.getStudyName();
            studyId = defaultStudyConfiguration.getStudyId();
            String[] cohortOpValue = VariantDBAdaptorUtils.splitOperator(filter);
            String cohort = cohortOpValue[0];
            cohortId = utils.getCohortId(cohort, defaultStudyConfiguration);
            operator = cohortOpValue[1];
            valueStr = cohortOpValue[2];
        }

        QueryBuilder statsBuilder = new QueryBuilder();
        statsBuilder.and(DocumentToVariantStatsConverter.STUDY_ID).is(studyId);
        if (cohortId != null) {
            statsBuilder.and(DocumentToVariantStatsConverter.COHORT_ID).is(cohortId);
        }
        addCompQueryFilter(key, valueStr, statsBuilder, operator);
        builder.and(DocumentToVariantConverter.STATS_FIELD).elemMatch(statsBuilder.get());
    } else {
        addCompQueryFilter(DocumentToVariantConverter.STATS_FIELD + "." + key, filter, builder, false);
    }
    return builder;
}