Example usage for com.mongodb QueryBuilder get

List of usage examples for com.mongodb QueryBuilder get

Introduction

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

Prototype

public DBObject get() 

Source Link

Document

Creates a DBObject query to be used for the driver's find operations

Usage

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

License:Apache License

@Override
public List<QueryResult> getAllGenesByPhenotypeList(List<String> phenotypeList, QueryOptions options) {
    List<DBObject> queries = new ArrayList<>(phenotypeList.size());
    for (String id : phenotypeList) {
        QueryBuilder builder = QueryBuilder.start("phenotype").is(id);
        queries.add(builder.get());
    }//from w w w  . ja v  a  2s .  c om
    return executeQueryList(phenotypeList, queries, options);
}

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

License:Apache License

@Override
public List<QueryResult> getByStartsWithQueryList(List<String> ids, QueryOptions options) {
    List<DBObject> queries = new ArrayList<>();

    for (String id : ids) {
        QueryBuilder qb = QueryBuilder.start("transcripts.xrefs.id").regex(Pattern.compile("^" + id));
        queries.add(qb.get());
    }/*from ww  w .j a  v a 2  s .c  om*/
    int limit = options.getInt("limit", 50);
    if (limit > 50) {
        options.put("limit", 50);
    }
    System.out.println(options.getInt("limit"));
    options.put("include", Arrays.asList("chromosome", "start", "end", "id", "name"));

    return executeQueryList(ids, queries, options);
}

From source file:org.opencb.cellbase.mongodb.impl.ConservationMongoDBAdaptor.java

License:Apache License

@Override
@Deprecated//w w w.  j  ava  2  s. c  om
public List<QueryResult> getAllScoresByRegionList(List regionList, QueryOptions options) {
    //TODO not finished yet
    List<Document> queries = new ArrayList<>();
    List<String> ids = new ArrayList<>(regionList.size());
    List<Integer> integerChunkIds;

    List<Region> regions = regionList;
    for (Region region : regions) {
        integerChunkIds = new ArrayList<>();
        // positions below 1 are not allowed
        if (region.getStart() < 1) {
            region.setStart(1);
        }
        if (region.getEnd() < 1) {
            region.setEnd(1);
        }

        /****/
        QueryBuilder builder;
        int regionChunkStart = getChunkId(region.getStart(),
                MongoDBCollectionConfiguration.CONSERVATION_CHUNK_SIZE);
        int regionChunkEnd = getChunkId(region.getEnd(),
                MongoDBCollectionConfiguration.CONSERVATION_CHUNK_SIZE);
        if (regionChunkStart == regionChunkEnd) {
            builder = QueryBuilder.start("_chunkIds").is(getChunkIdPrefix(region.getChromosome(),
                    region.getStart(), MongoDBCollectionConfiguration.CONSERVATION_CHUNK_SIZE));
        } else {
            //                for (int chunkId = regionChunkStart; chunkId <= regionChunkEnd; chunkId++) {
            //                    integerChunkIds.add(chunkId);
            //                }
            //    //            QueryBuilder builder = QueryBuilder.start("chromosome").is(region.getChromosomeInfo()).and("chunkId").in(hunkIds);
            //                builder = QueryBuilder.start("chromosome").is(region.getChromosomeInfo()).and("chunkId").in(integerChunkIds);
            builder = QueryBuilder.start("chromosome").is(region.getChromosome()).and("end")
                    .greaterThanEquals(region.getStart()).and("start").lessThanEquals(region.getEnd());
        }
        /****/

        queries.add(new Document(builder.get().toMap()));
        ids.add(region.toString());

        //            logger.debug(builder.get().toString());

    }
    List<QueryResult> queryResults = executeQueryList2(ids, queries, options);
    //        List<QueryResult> queryResults = executeQueryList(ids, queries, options);

    for (int i = 0; i < regions.size(); i++) {
        Region region = regions.get(i);
        QueryResult queryResult = queryResults.get(i);
        List<Document> list = (List<Document>) queryResult.getResult();

        Map<String, List<Float>> typeMap = new HashMap();

        //            int start = region.getStart();

        for (int j = 0; j < list.size(); j++) {
            Document chunk = list.get(j);

            if (!chunk.isEmpty()) {
                //                    BasicDBList valuesChunk = (BasicDBList) chunk.get("values");
                ArrayList valuesChunk = chunk.get("values", ArrayList.class);

                if (valuesChunk != null) { // TODO: temporary patch to skip empty chunks - remove as soon as conservation is reloaded
                    String source = chunk.getString("source");
                    List<Float> valuesList;
                    if (!typeMap.containsKey(source)) {
                        valuesList = new ArrayList<>(region.getEnd() - region.getStart() + 1);
                        for (int val = 0; val < region.getEnd() - region.getStart() + 1; val++) {
                            valuesList.add(null);
                        }
                        typeMap.put(source, valuesList);
                    } else {
                        valuesList = typeMap.get(source);
                    }

                    //                        valuesChunk = (BasicDBList) chunk.get("values");
                    valuesChunk = chunk.get("values", ArrayList.class);
                    int pos = 0;
                    if (region.getStart() > chunk.getInteger("start")) {
                        pos = region.getStart() - chunk.getInteger("start");
                    }

                    for (; pos < valuesChunk.size()
                            && (pos + chunk.getInteger("start") <= region.getEnd()); pos++) {
                        valuesList.set(pos + chunk.getInteger("start") - region.getStart(),
                                new Float((Double) valuesChunk.get(pos)));
                    }
                } else {
                    continue;
                }

            }

            BasicDBList resultList = new BasicDBList();
            for (Map.Entry<String, List<Float>> elem : typeMap.entrySet()) {
                for (Float value : elem.getValue()) {
                    if (value != null) {
                        resultList.add(new Score(new Double(value), elem.getKey()));
                    }
                }
            }
            if (!resultList.isEmpty()) {
                queryResult.setResult(resultList);
            } else {
                queryResult.setResult(null);
            }
        }

    }
    return queryResults;
}

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  ww  .j  a v a2s  . co m
            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

private StudyConfiguration parseStudyQueryParams(Query query, QueryBuilder builder) {

    if (query != null) {
        Map<String, Integer> studies = getStudyConfigurationManager().getStudies(null);

        boolean singleStudy = studies.size() == 1;
        boolean validStudiesFilter = isValidParam(query, VariantQueryParams.STUDIES);
        // SAMPLES filter will add a FILES filter if absent
        boolean validFilesFilter = isValidParam(query, VariantQueryParams.FILES)
                || isValidParam(query, VariantQueryParams.SAMPLES);
        boolean otherFilters = isValidParam(query, VariantQueryParams.FILES)
                || isValidParam(query, VariantQueryParams.GENOTYPE)
                || isValidParam(query, VariantQueryParams.SAMPLES)
                || isValidParam(query, VariantQueryParams.FILTER);

        // Use an elemMatch with all the study filters if there is more than one study registered,
        // or FILES and STUDIES filters are being used.
        // If filters STUDIES+FILES is used, elemMatch is required to use the index correctly. See #493
        boolean studyElemMatch = (!singleStudy || (validFilesFilter && validStudiesFilter));

        // If only studyId filter is being used, elemMatch is not needed
        if (validStudiesFilter && !otherFilters) {
            studyElemMatch = false;/*from  www.  ja  v  a 2  s .co m*/
        }

        // If using an elemMatch for the study, keys don't need to start with "studies"
        String studyQueryPrefix = studyElemMatch ? "" : DocumentToVariantConverter.STUDIES_FIELD + '.';
        QueryBuilder studyBuilder = QueryBuilder.start();
        final StudyConfiguration defaultStudyConfiguration = utils.getDefaultStudyConfiguration(query, null);

        if (isValidParam(query, VariantQueryParams.STUDIES)) {
            String sidKey = DocumentToVariantConverter.STUDIES_FIELD + '.'
                    + DocumentToStudyVariantEntryConverter.STUDYID_FIELD;
            String value = query.getString(VariantQueryParams.STUDIES.key());

            // Check that the study exists
            QueryOperation studiesOperation = checkOperator(value);
            List<String> studiesNames = splitValue(value, studiesOperation);
            List<Integer> studyIds = utils.getStudyIds(studiesNames, studies); // Non negated studyIds

            // If the Studies query has an AND operator or includes negated fields, it can not be represented only
            // in the "elemMatch". It needs to be in the root
            boolean anyNegated = studiesNames.stream().anyMatch(VariantDBAdaptorUtils::isNegated);
            boolean studyFilterAtRoot = studiesOperation == QueryOperation.AND || anyNegated;
            if (studyFilterAtRoot) {
                addQueryFilter(sidKey, value, builder, QueryOperation.AND,
                        study -> utils.getStudyId(study, false, studies));
            }

            // Add all non negated studies to the elemMatch builder if it is being used,
            // or it is not and it has not been added to the root
            if (studyElemMatch || !studyFilterAtRoot) {
                if (!studyIds.isEmpty()) {
                    if (!singleStudy || anyNegated || validFilesFilter) {
                        String studyIdsCsv = studyIds.stream().map(Object::toString)
                                .collect(Collectors.joining(","));
                        addQueryIntegerFilter(
                                studyQueryPrefix + DocumentToStudyVariantEntryConverter.STUDYID_FIELD,
                                studyIdsCsv, studyBuilder, QueryOperation.AND);
                    } // There is only one study! We can skip this filter
                }
            }
        }

        if (isValidParam(query, VariantQueryParams.FILES)) {
            addQueryFilter(
                    studyQueryPrefix + DocumentToStudyVariantEntryConverter.FILES_FIELD + '.'
                            + DocumentToStudyVariantEntryConverter.FILEID_FIELD,
                    query.getString(VariantQueryParams.FILES.key()), studyBuilder, QueryOperation.AND,
                    f -> utils.getFileId(f, false, defaultStudyConfiguration));
        }

        if (isValidParam(query, VariantQueryParams.FILTER)) {
            String filesValue = query.getString(VariantQueryParams.FILES.key());
            QueryOperation filesOperation = checkOperator(filesValue);
            List<String> fileNames = splitValue(filesValue, filesOperation);
            List<Integer> fileIds = utils.getFileIds(fileNames, true, defaultStudyConfiguration);

            String fileQueryPrefix;
            if (fileIds.isEmpty()) {
                fileQueryPrefix = studyQueryPrefix + DocumentToStudyVariantEntryConverter.FILES_FIELD + '.';
                addQueryStringFilter(
                        fileQueryPrefix + DocumentToStudyVariantEntryConverter.ATTRIBUTES_FIELD + '.'
                                + StudyEntry.FILTER,
                        query.getString(VariantQueryParams.FILTER.key()), studyBuilder, QueryOperation.AND);
            } else {
                QueryBuilder fileBuilder = QueryBuilder.start();
                addQueryStringFilter(
                        DocumentToStudyVariantEntryConverter.ATTRIBUTES_FIELD + '.' + StudyEntry.FILTER,
                        query.getString(VariantQueryParams.FILTER.key()), fileBuilder, QueryOperation.AND);
                fileBuilder.and(DocumentToStudyVariantEntryConverter.FILEID_FIELD).in(fileIds);
                studyBuilder.and(studyQueryPrefix + DocumentToStudyVariantEntryConverter.FILES_FIELD)
                        .elemMatch(fileBuilder.get());
            }
        }

        Map<Object, List<String>> genotypesFilter = new HashMap<>();
        if (isValidParam(query, VariantQueryParams.GENOTYPE)) {
            String sampleGenotypes = query.getString(VariantQueryParams.GENOTYPE.key());
            parseGenotypeFilter(sampleGenotypes, genotypesFilter);
        }

        if (isValidParam(query, VariantQueryParams.SAMPLES)) {
            Set<Integer> files = new HashSet<>();
            String samples = query.getString(VariantQueryParams.SAMPLES.key());

            for (String sample : samples.split(",")) {
                int sampleId = utils.getSampleId(sample, defaultStudyConfiguration);
                genotypesFilter.put(sampleId,
                        Arrays.asList("1", "0/1", "0|1", "1|0", "1/1", "1|1", "1/2", "1|2", "2|1"));
                if (!isValidParam(query, VariantQueryParams.FILES) && defaultStudyConfiguration != null) {
                    for (Integer file : defaultStudyConfiguration.getIndexedFiles()) {
                        if (defaultStudyConfiguration.getSamplesInFiles().get(file).contains(sampleId)) {
                            files.add(file);
                        }
                    }
                }
            }

            // If there is no valid files filter, add files filter to speed up this query
            if (!isValidParam(query, VariantQueryParams.FILES) && !files.isEmpty()) {
                addQueryFilter(
                        studyQueryPrefix + DocumentToStudyVariantEntryConverter.FILES_FIELD + '.'
                                + DocumentToStudyVariantEntryConverter.FILEID_FIELD,
                        files, studyBuilder, QueryOperation.AND,
                        f -> utils.getFileId(f, false, defaultStudyConfiguration));
            }
        }

        if (!genotypesFilter.isEmpty()) {
            for (Map.Entry<Object, List<String>> entry : genotypesFilter.entrySet()) {
                Object sample = entry.getKey();
                List<String> genotypes = entry.getValue();

                int sampleId = utils.getSampleId(sample, defaultStudyConfiguration);

                QueryBuilder genotypesBuilder = QueryBuilder.start();

                List<String> defaultGenotypes;
                if (defaultStudyConfiguration != null) {
                    defaultGenotypes = defaultStudyConfiguration.getAttributes()
                            .getAsStringList(DEFAULT_GENOTYPE.key());
                } else {
                    defaultGenotypes = Arrays.asList("0/0", "0|0");
                }
                for (String genotype : genotypes) {
                    boolean negated = isNegated(genotype);
                    if (negated) {
                        genotype = genotype.substring(1);
                    }
                    if (defaultGenotypes.contains(genotype)) {
                        List<String> otherGenotypes = Arrays.asList("0/0", "0|0", "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", DocumentToSamplesConverter.UNKNOWN_GENOTYPE);
                        if (negated) {
                            for (String otherGenotype : otherGenotypes) {
                                if (defaultGenotypes.contains(otherGenotype)) {
                                    continue;
                                }
                                String key = studyQueryPrefix
                                        + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + '.'
                                        + otherGenotype;
                                genotypesBuilder.or(new BasicDBObject(key, sampleId));
                            }
                        } else {
                            QueryBuilder andBuilder = QueryBuilder.start();
                            for (String otherGenotype : otherGenotypes) {
                                if (defaultGenotypes.contains(otherGenotype)) {
                                    continue;
                                }
                                String key = studyQueryPrefix
                                        + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + '.'
                                        + otherGenotype;
                                andBuilder.and(new BasicDBObject(key, new Document("$ne", sampleId)));
                            }
                            genotypesBuilder.or(andBuilder.get());
                        }
                    } else {
                        String s = studyQueryPrefix + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + '.'
                                + DocumentToSamplesConverter.genotypeToStorageType(genotype);
                        if (negated) {
                            //and [ {"gt.0|1" : { $ne : <sampleId> } } ]
                            genotypesBuilder.and(new BasicDBObject(s, new BasicDBObject("$ne", sampleId)));

                        } else {
                            //or [ {"gt.0|1" : <sampleId> } ]
                            genotypesBuilder.or(new BasicDBObject(s, sampleId));
                        }
                    }
                }
                studyBuilder.and(genotypesBuilder.get());
            }
        }

        // If Study Query is used then we add a elemMatch query
        DBObject studyQuery = studyBuilder.get();
        if (!studyQuery.keySet().isEmpty()) {
            if (studyElemMatch) {
                builder.and(DocumentToVariantConverter.STUDIES_FIELD).elemMatch(studyQuery);
            } else {
                builder.and(studyQuery);
            }
        }
        return defaultStudyConfiguration;
    } else {
        return null;
    }
}

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

License:Apache License

private <T> QueryBuilder addQueryFilter(String key, String value, final QueryBuilder builder, QueryOperation op,
        Function<String, T> map) {
    QueryOperation operation = checkOperator(value);
    QueryBuilder auxBuilder;
    if (op == QueryOperation.OR) {
        auxBuilder = QueryBuilder.start();
    } else {//  w  w w  .  ja va2  s. com
        auxBuilder = builder;
    }

    if (operation == null) {
        if (value.startsWith("!")) {
            T mapped = map.apply(value.substring(1));
            if (mapped instanceof Collection) {
                auxBuilder.and(key).notIn(mapped);
            } else {
                auxBuilder.and(key).notEquals(mapped);
            }
        } else {
            T mapped = map.apply(value);
            if (mapped instanceof Collection) {
                auxBuilder.and(key).in(mapped);
            } else {
                auxBuilder.and(key).is(mapped);
            }
        }
    } else if (operation == QueryOperation.OR) {
        String[] array = value.split(OR);
        List list = new ArrayList(array.length);
        for (String elem : array) {
            if (elem.startsWith("!")) {
                throw new VariantQueryException(
                        "Unable to use negate (!) operator in OR sequences (<it_1>(,<it_n>)*)");
            } else {
                T mapped = map.apply(elem);
                if (mapped instanceof Collection) {
                    list.addAll(((Collection) mapped));
                } else {
                    list.add(mapped);
                }
            }
        }
        auxBuilder.and(key).in(list);
    } else {
        //Split in two lists: positive and negative
        String[] array = value.split(AND);
        List listIs = new ArrayList(array.length);
        List listNotIs = new ArrayList(array.length);

        for (String elem : array) {
            if (elem.startsWith("!")) {
                T mapped = map.apply(elem.substring(1));
                if (mapped instanceof Collection) {
                    listNotIs.addAll(((Collection) mapped));
                } else {
                    listNotIs.add(mapped);
                }
            } else {
                T mapped = map.apply(elem);
                if (mapped instanceof Collection) {
                    listIs.addAll(((Collection) mapped));
                } else {
                    listIs.add(mapped);
                }
            }
        }

        if (!listIs.isEmpty()) { //Can not use method "is" because it will be overwritten with the "notEquals" or "notIn" method
            auxBuilder.and(key).all(listIs);
        }
        if (listNotIs.size() == 1) {
            auxBuilder.and(key).notEquals(listNotIs.get(0));
        } else if (listNotIs.size() > 1) {
            auxBuilder.and(key).notIn(listNotIs);
        }

    }

    if (op == QueryOperation.OR) {
        builder.or(auxBuilder.get());
    }
    return builder;
}

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

License:Apache License

/**
 * Accept a list of comparative filters separated with "," or ";" with the expression:
 * {OPERATION}{VALUE}, where the accepted operations are: <, <=, >, >=, =, ==, !=, ~=.
 *
 * @param key/*from ww w .  j a v a2s  . co m*/
 * @param value
 * @param builder
 * @param extendKey
 * @return
 */
private QueryBuilder addCompListQueryFilter(String key, String value, QueryBuilder builder, boolean extendKey) {
    QueryOperation op = checkOperator(value);
    List<String> values = splitValue(value, op);

    QueryBuilder compBuilder;
    if (op == QueryOperation.OR) {
        compBuilder = QueryBuilder.start();
    } else {
        compBuilder = builder;
    }

    for (String elem : values) {
        addCompQueryFilter(key, elem, compBuilder, extendKey);
    }

    if (op == QueryOperation.OR) {
        builder.or(compBuilder.get());
    }
    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: {SOURCE}{OPERATION}{VALUE}.
 *
 * @param value         Value to parse/*from  ww  w.j ava2s  .  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/*from  ww w.j a  v  a  2  s  . c  o m*/
 * @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

/**
 * 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//  w  ww  .  j  a v a2 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;
}