Example usage for com.mongodb QueryBuilder and

List of usage examples for com.mongodb QueryBuilder and

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public QueryBuilder and(final DBObject... ands) 

Source Link

Document

Equivalent to an $and operand

Usage

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//from  ww  w.  j a  va  2 s .  com
 */
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  ww.j  ava  2 s .c om
 */
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;
}

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

License:Apache License

private QueryBuilder getRegionFilter(Region region, QueryBuilder builder) {
    List<String> chunkIds = getChunkIds(region);
    builder.and(DocumentToVariantConverter.AT_FIELD + '.' + DocumentToVariantConverter.CHUNK_IDS_FIELD)
            .in(chunkIds);//from  w  w w . j  av a  2 s . c  o  m
    builder.and(DocumentToVariantConverter.END_FIELD).greaterThanEquals(region.getStart());
    builder.and(DocumentToVariantConverter.START_FIELD).lessThanEquals(region.getEnd());
    return builder;
}

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

License:Apache License

private QueryBuilder getStudyFilter(String name, QueryBuilder builder) {
    return builder.and(DBObjectToVariantSourceConverter.STUDYNAME_FIELD).is(name);
}

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

License:Apache License

private QueryBuilder getStudyIdFilter(String id, QueryBuilder builder) {
    return builder.and(DBObjectToVariantSourceConverter.STUDYID_FIELD).is(id);
}

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

License:Apache License

private QueryBuilder parseQuery(Query query, QueryBuilder builder) {
    if (query != null) {

        /** VARIANT PARAMS **/

        if (query.containsKey(VariantQueryParams.REGION.key())
                && !query.getString(VariantQueryParams.REGION.key()).isEmpty()) {
            List<String> stringList = query.getAsStringList(VariantQueryParams.REGION.key());
            List<Region> regions = new ArrayList<>(stringList.size());
            for (String reg : stringList) {
                Region region = Region.parseRegion(reg);
                regions.add(region);//from  w w w .  j  a  va  2s  .  co  m
            }
            getRegionFilter(regions, builder);
        }

        if (query.getString(VariantQueryParams.ID.key()) != null
                && !query.getString(VariantQueryParams.ID.key()).isEmpty()) {
            List<String> ids = query.getAsStringList(VariantQueryParams.ID.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    ids, builder, QueryOperation.OR);
            addQueryListFilter(DBObjectToVariantConverter.IDS_FIELD, ids, builder, QueryOperation.OR);
        }

        if (query.containsKey(VariantQueryParams.GENE.key())) {
            List<String> xrefs = query.getAsStringList(VariantQueryParams.GENE.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    xrefs, builder, QueryOperation.OR);
        }

        if (query.containsKey(VariantQueryParams.REFERENCE.key())
                && query.getString(VariantQueryParams.REFERENCE.key()) != null) {
            addQueryStringFilter(DBObjectToVariantConverter.REFERENCE_FIELD,
                    query.getString(VariantQueryParams.REFERENCE.key()), builder);
        }

        if (query.containsKey(VariantQueryParams.ALTERNATE.key())
                && query.getString(VariantQueryParams.ALTERNATE.key()) != null) {
            addQueryStringFilter(DBObjectToVariantConverter.ALTERNATE_FIELD,
                    query.getString(VariantQueryParams.ALTERNATE.key()), builder);
        }

        if (query.containsKey(VariantQueryParams.TYPE.key())
                && !query.getString(VariantQueryParams.TYPE.key()).isEmpty()) {
            addQueryStringFilter(DBObjectToVariantConverter.TYPE_FIELD,
                    query.getString(VariantQueryParams.TYPE.key()), builder);
        }

        /** ANNOTATION PARAMS **/

        if (query.containsKey(VariantQueryParams.ANNOTATION_EXISTS.key())) {
            builder.and(DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                    + DBObjectToVariantAnnotationConverter.ANNOT_ID_FIELD);
            builder.exists(query.getBoolean(VariantQueryParams.ANNOTATION_EXISTS.key()));
        }

        if (query.containsKey(VariantQueryParams.ANNOT_XREF.key())) {
            List<String> xrefs = query.getAsStringList(VariantQueryParams.ANNOT_XREF.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREFS_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.XREF_ID_FIELD,
                    xrefs, builder, QueryOperation.AND);
        }

        if (query.containsKey(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key())) {
            List<String> cts = new ArrayList<>(
                    query.getAsStringList(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key()));
            List<Integer> ctsInteger = new ArrayList<>(cts.size());
            for (Iterator<String> iterator = cts.iterator(); iterator.hasNext();) {
                String ct = iterator.next();
                if (ct.startsWith("SO:")) {
                    ct = ct.substring(3);
                }
                try {
                    ctsInteger.add(Integer.parseInt(ct));
                } catch (NumberFormatException e) {
                    logger.error("Error parsing integer ", e);
                    iterator.remove(); //Remove the malformed query params.
                }
            }
            query.put(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key(), cts);
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SO_ACCESSION_FIELD,
                    ctsInteger, builder, QueryOperation.AND);
        }

        if (query.containsKey(VariantQueryParams.ANNOT_BIOTYPE.key())) {
            List<String> biotypes = query.getAsStringList(VariantQueryParams.ANNOT_BIOTYPE.key());
            addQueryListFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.BIOTYPE_FIELD,
                    biotypes, builder, QueryOperation.AND);
        }

        if (query.containsKey(VariantQueryParams.POLYPHEN.key())) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POLYPHEN_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SCORE_SCORE_FIELD,
                    query.getString(VariantQueryParams.POLYPHEN.key()), builder);
        }

        if (query.containsKey(VariantQueryParams.SIFT.key())) {
            System.out.println(query.getString(VariantQueryParams.SIFT.key()));
            addCompQueryFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SIFT_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.SCORE_SCORE_FIELD,
                    query.getString(VariantQueryParams.SIFT.key()), builder);
        }

        if (query.containsKey(VariantQueryParams.PROTEIN_SUBSTITUTION.key())) {
            List<String> list = new ArrayList<>(
                    query.getAsStringList(VariantQueryParams.PROTEIN_SUBSTITUTION.key()));
            addScoreFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.CONSEQUENCE_TYPE_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.PROTEIN_SUBSTITUTION_SCORE_FIELD,
                    list, builder);
            query.put(VariantQueryParams.PROTEIN_SUBSTITUTION.key(), list); //Replace the QueryOption without the malformed query params
        }

        if (query.containsKey(VariantQueryParams.CONSERVATION.key())) {
            List<String> list = new ArrayList<>(query.getAsStringList(VariantQueryParams.CONSERVATION.key()));
            addScoreFilter(DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                    + DBObjectToVariantAnnotationConverter.CONSERVED_REGION_SCORE_FIELD, list, builder);
            query.put(VariantQueryParams.CONSERVATION.key(), list);
        }

        if (query.containsKey(VariantQueryParams.ALTERNATE_FREQUENCY.key())) {
            List<String> list = new ArrayList<>(
                    query.getAsStringList(VariantQueryParams.ALTERNATE_FREQUENCY.key()));
            addFrequencyFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCIES_FIELD,
                    DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_ALTERNATE_FREQUENCY_FIELD, list,
                    builder); // Same method addFrequencyFilter is used for reference and allele frequencies. Need to provide the field (reference/alternate) where to check the frequency
        }

        if (query.containsKey(VariantQueryParams.REFERENCE_FREQUENCY.key())) {
            List<String> list = new ArrayList<>(
                    query.getAsStringList(VariantQueryParams.REFERENCE_FREQUENCY.key()));
            addFrequencyFilter(
                    DBObjectToVariantConverter.ANNOTATION_FIELD + "."
                            + DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCIES_FIELD,
                    DBObjectToVariantAnnotationConverter.POPULATION_FREQUENCY_REFERENCE_FREQUENCY_FIELD, list,
                    builder); // Same method addFrequencyFilter is used for reference and allele frequencies. Need to provide the field (reference/alternate) where to check the frequency
        }

        /** STATS PARAMS **/

        if (query.get(VariantQueryParams.STATS_MAF.key()) != null
                && !query.getString(VariantQueryParams.STATS_MAF.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "." + DBObjectToVariantStatsConverter.MAF_FIELD,
                    query.getString(VariantQueryParams.STATS_MAF.key()), builder);
        }

        if (query.get(VariantQueryParams.STATS_MGF.key()) != null
                && !query.getString(VariantQueryParams.STATS_MGF.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "." + DBObjectToVariantStatsConverter.MGF_FIELD,
                    query.getString(VariantQueryParams.STATS_MGF.key()), builder);
        }

        if (query.get(VariantQueryParams.MISSING_ALLELES.key()) != null
                && !query.getString(VariantQueryParams.MISSING_ALLELES.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "."
                            + DBObjectToVariantStatsConverter.MISSALLELE_FIELD,
                    query.getString(VariantQueryParams.MISSING_ALLELES.key()), builder);
        }

        if (query.get(VariantQueryParams.MISSING_GENOTYPES.key()) != null
                && !query.getString(VariantQueryParams.MISSING_GENOTYPES.key()).isEmpty()) {
            addCompQueryFilter(
                    DBObjectToVariantConverter.STATS_FIELD + "."
                            + DBObjectToVariantStatsConverter.MISSGENOTYPE_FIELD,
                    query.getString(VariantQueryParams.MISSING_GENOTYPES.key()), builder);
        }

        if (query.get("numgt") != null && !query.getString("numgt").isEmpty()) {
            for (String numgt : query.getAsStringList("numgt")) {
                String[] split = numgt.split(":");
                addCompQueryFilter(
                        DBObjectToVariantConverter.STATS_FIELD + "."
                                + DBObjectToVariantStatsConverter.NUMGT_FIELD + "." + split[0],
                        split[1], builder);
            }
        }

        /** STUDIES **/
        QueryBuilder studyBuilder = QueryBuilder.start();

        if (query.containsKey(VariantQueryParams.STUDIES.key())) { // && !options.getList("studies").isEmpty() && !options.getListAs("studies", String.class).get(0).isEmpty()) {
            List<Integer> studyIds = getStudyIds(query.getAsList(VariantQueryParams.STUDIES.key()), null);
            addQueryListFilter(DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, studyIds, studyBuilder,
                    QueryOperation.AND);
        }

        if (query.containsKey(VariantQueryParams.FILES.key())) { // && !options.getList("files").isEmpty() && !options.getListAs("files", String.class).get(0).isEmpty()) {
            addQueryListFilter(
                    DBObjectToVariantSourceEntryConverter.FILES_FIELD + "."
                            + DBObjectToVariantSourceEntryConverter.FILEID_FIELD,
                    query.getAsIntegerList(VariantQueryParams.FILES.key()), studyBuilder, QueryOperation.AND);
        }

        if (query.containsKey(VariantQueryParams.GENOTYPE.key())) {
            String sampleGenotypesCSV = query.getString(VariantQueryParams.GENOTYPE.key());

            //                String AND = ",";
            //                String OR = ";";
            //                String IS = ":";

            //                String AND = "AND";
            //                String OR = "OR";
            //                String IS = ":";

            String AND = ";";
            String OR = ",";
            String IS = ":";

            // we may need to know the study type
            //                studyConfigurationManager.getStudyConfiguration(1, null).getResult().get(0).

            String[] sampleGenotypesArray = sampleGenotypesCSV.split(AND);
            System.out.println("sampleGenotypesArray = " + Arrays.toString(sampleGenotypesArray));

            for (String sampleGenotypes : sampleGenotypesArray) {
                String[] sampleGenotype = sampleGenotypes.split(IS);
                if (sampleGenotype.length != 2) {
                    continue;
                }
                int sample = Integer.parseInt(sampleGenotype[0]);
                String[] genotypes = sampleGenotype[1].split(OR);
                QueryBuilder genotypesBuilder = QueryBuilder.start();
                for (String genotype : genotypes) {
                    if ("0/0".equals(genotype) || "0|0".equals(genotype)) {
                        QueryBuilder andBuilder = QueryBuilder.start();
                        List<String> otherGenotypes = Arrays.asList("0/1", "1/0", "1/1", "-1/-1", "0|1", "1|0",
                                "1|1", "-1|-1", "0|2", "2|0", "2|1", "1|2", "2|2", "0/2", "2/0", "2/1", "1/2",
                                "2/2", DBObjectToSamplesConverter.UNKNOWN_GENOTYPE);
                        for (String otherGenotype : otherGenotypes) {
                            andBuilder.and(new BasicDBObject(
                                    DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD + "." + otherGenotype,
                                    new BasicDBObject("$not", new BasicDBObject("$elemMatch",
                                            new BasicDBObject("$eq", sample)))));
                        }
                        genotypesBuilder.or(andBuilder.get());
                    } else {
                        String s = DBObjectToVariantSourceEntryConverter.GENOTYPES_FIELD + "."
                                + DBObjectToSamplesConverter.genotypeToStorageType(genotype);
                        //or [ {"samp.0|0" : { $elemMatch : { $eq : <sampleId> } } } ]
                        genotypesBuilder.or(new BasicDBObject(s,
                                new BasicDBObject("$elemMatch", new BasicDBObject("$eq", sample))));
                    }
                }
                studyBuilder.and(genotypesBuilder.get());
            }
        }

        // If Study Query is used then we add a elemMatch query
        DBObject studyQuery = studyBuilder.get();
        if (studyQuery.keySet().size() != 0) {
            builder.and(DBObjectToVariantConverter.STUDIES_FIELD).elemMatch(studyQuery);
        }
    }

    logger.debug("Find = " + builder.get());
    return builder;
}

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

License:Apache License

private QueryBuilder addQueryStringFilter(String key, String value, QueryBuilder builder) {
    if (value != null && !value.isEmpty()) {
        if (value.indexOf(",") == -1) {
            builder.and(key).is(value);
        } else {//  www .j a v a 2  s. co  m
            String[] values = value.split(",");
            builder.and(key).in(values);
        }
    }
    return builder;
}

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

License:Apache License

private QueryBuilder addQueryListFilter(String key, List<?> values, QueryBuilder builder, QueryOperation op) {
    if (values != null)
        if (values.size() == 1) {
            if (op == QueryOperation.AND) {
                builder.and(key).is(values.get(0));
            } else {
                builder.or(QueryBuilder.start(key).is(values.get(0)).get());
            }/*from www . ja v a2 s  . c  o m*/
        } else if (!values.isEmpty()) {
            if (op == QueryOperation.AND) {
                builder.and(key).in(values);
            } else {
                builder.or(QueryBuilder.start(key).in(values).get());
            }
        }
    return builder;
}

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

License:Apache License

private QueryBuilder addCompQueryFilter(String key, String value, QueryBuilder builder) {
    String op = value.substring(0, 2);
    op = op.replaceFirst("[0-9]", "");
    String obj = value.replaceFirst(op, "");

    switch (op) {
    case "<":
        builder.and(key).lessThan(Double.parseDouble(obj));
        break;/*  www  . j  av  a 2 s  .c  o  m*/
    case "<=":
        builder.and(key).lessThanEquals(Double.parseDouble(obj));
        break;
    case ">":
        builder.and(key).greaterThan(Double.parseDouble(obj));
        break;
    case ">=":
        builder.and(key).greaterThanEquals(Double.parseDouble(obj));
        break;
    case "=":
    case "==":
        builder.and(key).is(Double.parseDouble(obj));
        break;
    case "!=":
        builder.and(key).notEquals(Double.parseDouble(obj));
        break;
    case "~=":
        builder.and(key).regex(Pattern.compile(obj));
        break;
    }
    return builder;
}

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);/*from   w  w  w .  ja v  a2  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;
}