Example usage for com.mongodb QueryBuilder or

List of usage examples for com.mongodb QueryBuilder or

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public QueryBuilder or(final DBObject... ors) 

Source Link

Document

Equivalent to an $or operand

Usage

From source file:com.gigaspaces.persistency.parser.SQL2MongoBaseVisitor.java

License:Open Source License

public T visitOr(SQL2MongoParser.OrContext ctx) {

    T r = visitChildren(ctx);/* www  .  j a v a 2s  .  com*/

    if (IsLogic(ctx, "OR")) {

        QueryBuilder q = QueryBuilder.start();

        for (DBObject at : ands)
            q.or(at);

        Set<String> keys = atom.get().keySet();

        for (String key : keys) {
            q.or(new BasicDBObject(key, atom.get().get(key)));
        }

        ands.clear();
        atom = QueryBuilder.start();
        ors.add(q.get());
    }

    return r;
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java

License:Apache License

private <T extends Document> Map<String, T> findDocuments(Collection<T> collection, Set<String> keys) {
    Map<String, T> docs = new HashMap<String, T>();
    if (!keys.isEmpty()) {
        DBObject[] conditions = new DBObject[keys.size()];
        int i = 0;
        for (String key : keys) {
            conditions[i++] = getByKeyQuery(key).get();
        }/*from   ww w.  j  av a 2s. c  o m*/

        QueryBuilder builder = new QueryBuilder();
        builder.or(conditions);
        DBCursor cursor = getDBCollection(collection).find(builder.get());
        while (cursor.hasNext()) {
            T foundDoc = convertFromDBObject(collection, cursor.next());
            docs.put(foundDoc.getId(), foundDoc);
        }
    }
    return docs;
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoVersionGCSupport.java

License:Apache License

private DBObject createQuery(Set<SplitDocType> gcTypes, long oldestRevTimeStamp) {
    //OR condition has to be first as we have a index for that
    //((type == DEFAULT_NO_CHILD || type == PROP_COMMIT_ONLY ..) && _sdMaxRevTime < oldestRevTimeStamp(in secs)
    QueryBuilder orClause = start();
    for (SplitDocType type : gcTypes) {
        orClause.or(start(NodeDocument.SD_TYPE).is(type.typeCode()).get());
    }//from ww w . j a v a  2s. c o  m
    return start().and(orClause.get(), start(NodeDocument.SD_MAX_REV_TIME_IN_SECS)
            .lessThan(NodeDocument.getModifiedInSecs(oldestRevTimeStamp)).get()).get();
}

From source file:org.apache.rya.indexing.mongodb.IndexingMongoDBStorageStrategy.java

License:Apache License

public DBObject getQuery(final StatementConstraints contraints) {
    final QueryBuilder queryBuilder = QueryBuilder.start();
    if (contraints.hasSubject()) {
        queryBuilder.and(new BasicDBObject(SUBJECT, contraints.getSubject().toString()));
    }//from   w w  w.  j  a  va 2  s  .c  o  m

    if (contraints.hasPredicates()) {
        final Set<URI> predicates = contraints.getPredicates();
        if (predicates.size() > 1) {
            for (final URI pred : predicates) {
                final DBObject currentPred = new BasicDBObject(PREDICATE, pred.toString());
                queryBuilder.or(currentPred);
            }
        } else if (!predicates.isEmpty()) {
            queryBuilder.and(new BasicDBObject(PREDICATE, predicates.iterator().next().toString()));
        }
    }
    if (contraints.hasContext()) {
        queryBuilder.and(new BasicDBObject(CONTEXT, contraints.getContext().toString()));
    }
    return queryBuilder.get();
}

From source file:org.entcore.workspace.service.impl.WorkspaceSearchingEvents.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void searchResource(List<String> appFilters, final String userId, JsonArray groupIds,
        JsonArray searchWords, Integer page, Integer limit, final JsonArray columnsHeader, final String locale,
        final Handler<Either<String, JsonArray>> handler) {
    if (appFilters.contains(WorkspaceSearchingEvents.class.getSimpleName())) {

        final List<String> searchWordsLst = searchWords.getList();

        final List<String> groupIdsLst = groupIds.getList();
        final List<DBObject> groups = new ArrayList<>();
        groups.add(QueryBuilder.start("userId").is(userId).get());
        for (String gpId : groupIdsLst) {
            groups.add(QueryBuilder.start("groupId").is(gpId).get());
        }// w w w. j a  va  2  s.c o  m

        final QueryBuilder rightsQuery = new QueryBuilder().or(
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("owner").is(userId).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());

        final QueryBuilder worldsQuery = new QueryBuilder();
        worldsQuery.text(MongoDbSearchService.textSearchedComposition(searchWordsLst));

        //searching only the file entry (not folder), if folder match and is returned, the paginate system is impacted
        final QueryBuilder fileQuery = QueryBuilder.start("file").exists(true);

        final QueryBuilder query = new QueryBuilder().and(fileQuery.get(), rightsQuery.get(),
                worldsQuery.get());

        JsonObject sort = new JsonObject().put("modified", -1);
        final JsonObject projection = new JsonObject();
        projection.put("name", 1);
        projection.put("modified", 1);
        projection.put("folder", 1);
        projection.put("owner", 1);
        projection.put("ownerName", 1);
        projection.put("comments", 1);

        final int skip = (0 == page) ? -1 : page * limit;

        //main search on file
        mongo.find(this.collection, MongoQueryBuilder.build(query), sort, projection, skip, limit,
                Integer.MAX_VALUE, validResultsHandler(new Handler<Either<String, JsonArray>>() {
                    @Override
                    public void handle(Either<String, JsonArray> event) {

                        if (event.isRight()) {
                            final JsonArray globalJa = event.right().getValue();
                            //different owner can have the same folder name
                            //if the folder exists, we must find id of folder according to the directory name and the owner,
                            //it's necessary to use the front route for the resource link
                            final QueryBuilder foldersOwnersOrQuery = new QueryBuilder();
                            Boolean isFolderProcessing = false;

                            for (int i = 0; i < globalJa.size(); i++) {
                                final JsonObject j = globalJa.getJsonObject(i);

                                // processing only files that have a folder
                                if (j != null && !StringUtils.isEmpty(j.getString("folder"))) {
                                    isFolderProcessing = true;
                                    final QueryBuilder folderOwnerQuery = new QueryBuilder();
                                    folderOwnerQuery.and(
                                            QueryBuilder.start("folder").is(j.getString("folder")).get(),
                                            QueryBuilder.start("owner").is(j.getString("owner")).get());
                                    foldersOwnersOrQuery.or(folderOwnerQuery.get());
                                }
                            }

                            final Map<String, Map<String, String>> mapOwnerMapNameFolderId = new HashMap<>();
                            //finding ids of folder found.
                            if (isFolderProcessing) {
                                //find only authorized folder entry and not file
                                final QueryBuilder queryFindFolderIds = new QueryBuilder().and(
                                        QueryBuilder.start("file").exists(false).get(), rightsQuery.get(),
                                        foldersOwnersOrQuery.get());
                                //search all folder of main result set and format the search result
                                findFoldersIdAndFormatResult(globalJa, queryFindFolderIds, columnsHeader,
                                        searchWordsLst, locale, userId, handler);
                            } else {
                                //all files without folder
                                final JsonArray res = formatSearchResult(globalJa, columnsHeader,
                                        searchWordsLst, locale, userId, mapOwnerMapNameFolderId);
                                handler.handle(new Either.Right<String, JsonArray>(res));
                            }
                        } else {
                            handler.handle(new Either.Left<String, JsonArray>(event.left().getValue()));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "[WorkspaceSearchingEvents][searchResource] The resources searched by user are finded");
                        }
                    }
                }));
    } else {
        handler.handle(new Either.Right<String, JsonArray>(new fr.wseduc.webutils.collections.JsonArray()));
    }
}

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

License:Apache License

private QueryBuilder addClinvarPhenotypeFilter(QueryBuilder builder, QueryOptions options) {
    List<Object> phenotypeList = options.getList("phenotype", null);
    if (phenotypeList != null && phenotypeList.size() > 0) {
        QueryBuilder phenotypeQueryBuilder = QueryBuilder.start();
        for (Object phenotype : phenotypeList) {
            String phenotypeString = (String) phenotype;
            phenotypeQueryBuilder = phenotypeQueryBuilder
                    .or(QueryBuilder.start("referenceClinVarAssertion.traitSet.trait.name.elementValue.value")
                            .text(phenotypeString).get());
        }//from  w w  w . j  av  a  2s .c o  m
        builder = builder.and(phenotypeQueryBuilder.get());
    }
    return builder;
}

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

License:Apache License

private QueryBuilder addClinvarRegionFilter(QueryBuilder builder, QueryOptions options) {
    List<Object> regions = options.getList("region", null);
    BasicDBList regionList = new BasicDBList();
    if (regions != null) {
        Region region = (Region) regions.get(0);
        QueryBuilder regionQueryBuilder = QueryBuilder.start("chromosome").is(region.getChromosome()).and("end")
                .greaterThanEquals(region.getStart()).and("start").lessThanEquals(region.getEnd());
        for (int i = 1; i < regions.size(); i++) {
            region = (Region) regions.get(i);
            regionQueryBuilder = regionQueryBuilder.or(QueryBuilder.start("chromosome")
                    .is(region.getChromosome()).and("end").greaterThanEquals(region.getStart()).and("start")
                    .lessThanEquals(region.getEnd()).get());
        }/*  www.j  a  v a 2s  . c  o m*/
        builder = builder.and(regionQueryBuilder.get());
    }
    return builder;
}

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

License:Apache License

private QueryBuilder addClinvarIdFilter(QueryBuilder builder, QueryOptions options) {
    List<Object> idList = options.getList("id", null);
    if (idList != null && idList.size() > 0) {
        QueryBuilder idQueryBuilder = QueryBuilder.start();
        for (Object id : idList) {
            String idString = (String) id;
            if (idString.toLowerCase().startsWith("rs")) {
                idQueryBuilder = idQueryBuilder.or(QueryBuilder.start(
                        "clinvarList.clinvarSet.referenceClinVarAssertion.measureSet.measure.attributeSet.xref.type")
                        .is("rs")
                        .and("clinvarList.clinvarSet.referenceClinVarAssertion.measureSet.measure.attributeSet.xref.id")
                        .is(Integer.valueOf(idString.substring(2))).get());
            } else if (idString.toLowerCase().startsWith("rcv")) {
                idQueryBuilder = idQueryBuilder.or(QueryBuilder
                        .start("clinvarList.clinvarSet.referenceClinVarAssertion.clinVarAccession.acc")
                        .is(idString).get());
            }/*from   ww w  .j a v  a  2  s.  c  o  m*/
        }
        builder = builder.and(idQueryBuilder.get());
    }
    return builder;
}

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  2s  .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

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   w  w w . ja  v a 2  s .  com
        }

        // 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;
    }
}