Example usage for com.mongodb DBCursor hint

List of usage examples for com.mongodb DBCursor hint

Introduction

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

Prototype

@Deprecated
public DBCursor hint(final String indexName) 

Source Link

Document

Informs the database of an indexed field of the collection in order to improve performance.

Usage

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void find(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.findQuery)).getDBObject();
    final DBObject fields = ((DocBuilderField) getBoundUnit(Item.findFields)).getDBObject();
    final DBObject sort = ((DocBuilderField) getBoundUnit(Item.findSort)).getDBObject();
    final DBObject hint = ((DocBuilderField) getBoundUnit(Item.findHint)).getDBObject();
    final int skip = getIntFieldValue(Item.findSkip);
    final int limit = getIntFieldValue(Item.findLimit);
    final int batchSize = getIntFieldValue(Item.findBatchSize);
    final boolean explain = getBooleanFieldValue(Item.findExplain);
    final boolean export = getBooleanFieldValue(Item.findExport);

    if (export) {
        exportToFile(col, query, fields, sort, skip, limit, batchSize);
    } else {/*from ww  w .j ava2 s .c om*/
        new DbJob() {
            @Override
            public Object doRun() {
                // this does not actually block, may not need dbjob
                DBCursor cur = col.find(query, fields, skip, batchSize);
                if (sort != null) {
                    cur.sort(sort);
                }
                if (limit > 0) {
                    cur.limit(limit);
                }
                if (hint != null) {
                    cur.hint(hint);
                }
                if (explain) {
                    return cur.explain();
                }

                // force cursor to start
                cur.hasNext();
                return cur;
            }

            @Override
            public String getNS() {
                return col.getFullName();
            }

            @Override
            public String getShortName() {
                return "Find";
            }

            @Override
            public DBObject getRoot(Object result) {
                if (result == null || !(result instanceof DBCursor)) {
                    return null;
                }
                DBCursor res = (DBCursor) result;
                BasicDBObject obj = new BasicDBObject("cursorId", res.getCursorId());
                obj.put("server", res.getServerAddress().toString());
                obj.put("query", res.getQuery());
                obj.put("fields", res.getKeysWanted());
                obj.put("options", res.getOptions());
                obj.put("readPreference", res.getReadPreference().toDBObject());
                obj.put("numSeen", res.numSeen());
                obj.put("numGetMores", res.numGetMores());
                // want skip, limit, batchsize
                return obj;
            }

            @Override
            public ButtonBase getButton() {
                return button;
            }
        }.addJob();

    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

static void doFind(final DBCollection col, final DBObject query, final DBObject fields, final DBObject sort,
        final int skip, final int limit, final int batchSize, final boolean explain, final DBObject hint,
        final int options) {
    new DbJob() {
        @Override//from w  w  w . jav  a  2s  .  co  m
        public Object doRun() {
            // this does not actually block, may not need dbjob
            DBCursor cur = col.find(query, fields).skip(skip).batchSize(batchSize).addOption(options);
            if (sort != null) {
                cur.sort(sort);
            }
            if (limit > 0) {
                cur.limit(limit);
            }
            if (hint != null) {
                cur.hint(hint);
            }
            if (explain) {
                return cur.explain();
            }

            // force cursor to start
            cur.hasNext();
            return cur;
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Find";
        }

        @Override
        public DBObject getRoot(Object result) {
            if (result == null || !(result instanceof DBCursor)) {
                return null;
            }
            DBCursor res = (DBCursor) result;
            BasicDBObject obj = new BasicDBObject("cursorId", res.getCursorId());
            obj.put("query", res.getQuery());
            obj.put("fields", res.getKeysWanted());
            obj.put("options", res.getOptions());
            obj.put("readPreference", res.getReadPreference().toDBObject());
            obj.put("numSeen", res.numSeen());
            obj.put("numGetMores", res.numGetMores());
            // want skip, limit, batchsize
            return obj;
        }
    }.addJob();
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void doFind(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;/*from   w ww .j av  a 2  s.  c o m*/
    }
    Integer limit = (Integer) message.body().getNumber("limit");
    if (limit == null) {
        limit = -1;
    }
    Integer skip = (Integer) message.body().getNumber("skip");
    if (skip == null) {
        skip = -1;
    }
    Integer batchSize = (Integer) message.body().getNumber("batch_size");
    if (batchSize == null) {
        batchSize = 100;
    }
    Integer timeout = (Integer) message.body().getNumber("timeout");
    if (timeout == null || timeout < 0) {
        timeout = 10000; // 10 seconds
    }
    JsonObject matcher = message.body().getObject("matcher");
    JsonObject keys = message.body().getObject("keys");

    Object hint = message.body().getField("hint");
    Object sort = message.body().getField("sort");
    DBCollection coll = db.getCollection(collection);
    DBCursor cursor;
    if (matcher != null) {
        cursor = (keys == null) ? coll.find(jsonToDBObject(matcher))
                : coll.find(jsonToDBObject(matcher), jsonToDBObject(keys));
    } else {
        cursor = coll.find();
    }
    if (skip != -1) {
        cursor.skip(skip);
    }
    if (limit != -1) {
        cursor.limit(limit);
    }
    if (sort != null) {
        cursor.sort(sortObjectToDBObject(sort));
    }
    if (hint != null) {
        if (hint instanceof JsonObject) {
            cursor.hint(jsonToDBObject((JsonObject) hint));
        } else if (hint instanceof String) {
            cursor.hint((String) hint);
        } else {
            throw new IllegalArgumentException("Cannot handle type " + hint.getClass().getSimpleName());
        }
    }
    sendBatch(message, cursor, batchSize, timeout);
}

From source file:io.liveoak.mongo.MongoCollectionResource.java

License:Open Source License

@Override
public Collection<Resource> members(RequestContext ctx) throws Exception {

    LinkedList<Resource> members = new LinkedList<>();

    DBObject returnFields = new BasicDBObject();
    if (ctx.returnFields() != null && !ctx.returnFields().child(LiveOak.MEMBERS).isEmpty()) {
        ReturnFields membersReturnFields = ctx.returnFields().child(LiveOak.MEMBERS);
        if (!membersReturnFields.isAll()) {
            membersReturnFields.forEach((fieldName) -> {
                returnFields.put(fieldName, true);
            });//w w w . j  a  v  a  2  s.  c  om
        }
    }

    DBCursor dbCursor = dbCollection.find(queryObject, returnFields);

    ResourceParams resourceParams = ctx.resourceParams();
    if (resourceParams != null && resourceParams.contains("hint")) {
        String hint = resourceParams.value("hint");
        if (hint.startsWith("{")) {
            try {
                DBObject hintObject = (DBObject) JSON.parse(hint);
                dbCursor.hint(hintObject);
            } catch (Exception e) {
                throw new NotAcceptableException(uri().toString(),
                        "Invalid JSON format for the 'hint' parameter", e);
            }
        } else {
            dbCursor.hint(hint);
        }
    }

    if (explainQuery) {
        members.add(new MongoEmbeddedObjectResource(this, dbCursor.explain()));
    } else {
        Sorting sorting = ctx.sorting();
        if (sorting != null) {
            BasicDBObject sortingObject = new BasicDBObject();
            for (Sorting.Spec spec : sorting) {
                sortingObject.append(spec.name(), spec.ascending() ? 1 : -1);
            }
            dbCursor = dbCursor.sort(sortingObject);
        }

        Pagination pagination = ctx.pagination();
        if (pagination != null) {
            dbCursor.limit(pagination.limit());
            dbCursor.skip(pagination.offset());
        }

        try {
            dbCursor.hasNext();
        } catch (Exception e) {
            throw new ResourceProcessingException(
                    "Exception encountered trying to fetch data from the Mongo Database", e);
        }

        dbCursor.forEach((dbObject) -> {
            members.add(new MongoBaseObjectResource(this, dbObject));
        });
    }

    return members;
}

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

License:Apache License

@SuppressWarnings("unchecked")
@Nonnull/*from www.  j a  v a  2s.co m*/
<T extends Document> List<T> queryInternal(Collection<T> collection, String fromKey, String toKey,
        String indexedProperty, long startValue, int limit, long maxQueryTime) {
    log("query", fromKey, toKey, indexedProperty, startValue, limit);
    DBCollection dbCollection = getDBCollection(collection);
    QueryBuilder queryBuilder = QueryBuilder.start(Document.ID);
    queryBuilder.greaterThan(fromKey);
    queryBuilder.lessThan(toKey);

    DBObject hint = new BasicDBObject(NodeDocument.ID, 1);

    if (indexedProperty != null) {
        if (NodeDocument.DELETED_ONCE.equals(indexedProperty)) {
            if (startValue != 1) {
                throw new DocumentStoreException("unsupported value for property " + NodeDocument.DELETED_ONCE);
            }
            queryBuilder.and(indexedProperty);
            queryBuilder.is(true);
        } else {
            queryBuilder.and(indexedProperty);
            queryBuilder.greaterThanEquals(startValue);

            if (NodeDocument.MODIFIED_IN_SECS.equals(indexedProperty) && canUseModifiedTimeIdx(startValue)) {
                hint = new BasicDBObject(NodeDocument.MODIFIED_IN_SECS, -1);
            }
        }
    }
    DBObject query = queryBuilder.get();
    String parentId = Utils.getParentIdFromLowerLimit(fromKey);
    long lockTime = -1;
    final Stopwatch watch = startWatch();

    boolean isSlaveOk = false;
    int resultSize = 0;
    CacheChangesTracker cacheChangesTracker = null;
    if (parentId != null && collection == Collection.NODES) {
        cacheChangesTracker = nodesCache.registerTracker(fromKey, toKey);
    }
    try {
        DBCursor cursor = dbCollection.find(query).sort(BY_ID_ASC);
        if (!disableIndexHint && !hasModifiedIdCompoundIndex) {
            cursor.hint(hint);
        }
        if (maxQueryTime > 0) {
            // OAK-2614: set maxTime if maxQueryTimeMS > 0
            cursor.maxTime(maxQueryTime, TimeUnit.MILLISECONDS);
        }
        ReadPreference readPreference = getMongoReadPreference(collection, parentId, null,
                getDefaultReadPreference(collection));

        if (readPreference.isSlaveOk()) {
            isSlaveOk = true;
            LOG.trace("Routing call to secondary for fetching children from [{}] to [{}]", fromKey, toKey);
        }

        cursor.setReadPreference(readPreference);

        List<T> list;
        try {
            list = new ArrayList<T>();
            for (int i = 0; i < limit && cursor.hasNext(); i++) {
                DBObject o = cursor.next();
                T doc = convertFromDBObject(collection, o);
                list.add(doc);
            }
            resultSize = list.size();
        } finally {
            cursor.close();
        }

        if (cacheChangesTracker != null) {
            nodesCache.putNonConflictingDocs(cacheChangesTracker, (List<NodeDocument>) list);
        }

        return list;
    } finally {
        if (cacheChangesTracker != null) {
            cacheChangesTracker.close();
        }
        stats.doneQuery(watch.elapsed(TimeUnit.NANOSECONDS), collection, fromKey, toKey,
                indexedProperty != null, resultSize, lockTime, isSlaveOk);
    }
}

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

License:Apache License

@Override
public CloseableIterable<NodeDocument> getPossiblyDeletedDocs(final long lastModifiedTime) {
    //_deletedOnce == true && _modified < lastModifiedTime
    DBObject query = start(NodeDocument.DELETED_ONCE).is(Boolean.TRUE).put(NodeDocument.MODIFIED_IN_SECS)
            .lessThan(NodeDocument.getModifiedInSecs(lastModifiedTime)).get();
    DBCursor cursor = getNodeCollection().find(query).setReadPreference(ReadPreference.secondaryPreferred());
    if (!disableIndexHint) {
        cursor.hint(new BasicDBObject(NodeDocument.DELETED_ONCE, 1));
    }/*from  w w  w .ja v  a 2  s . c om*/

    return CloseableIterable.wrap(transform(cursor, new Function<DBObject, NodeDocument>() {
        @Override
        public NodeDocument apply(DBObject input) {
            return store.convertFromDBObject(NODES, input);
        }
    }), cursor);
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java

License:Open Source License

/**
 * Applies data set query properties and hints on DBCursor, except
 * for cursor limit./*w w  w. ja va 2s.com*/
 * @see #applyPropertiesToCursor(DBCursor,QueryProperties,boolean,boolean)
 */
static void applyPropertiesToCursor(DBCursor rowsCursor, QueryProperties queryProps, boolean includeSortExpr) {
    if (includeSortExpr) // normally done only when executing a query to get full result set
    {
        DBObject sortExprObj = null;
        try {
            sortExprObj = queryProps.getSortExprAsParsedObject();
        } catch (OdaException ex) {
            // log warning and ignore
            DriverUtil.getLogger().log(Level.WARNING,
                    Messages.bind("Unable to parse the user-defined Sort Expression: {0}", //$NON-NLS-1$
                            queryProps.getSortExpr()), ex);
        }

        if (sortExprObj != null)
            rowsCursor.sort(sortExprObj);
    }

    ReadPreference readPref = queryProps.getTaggableReadPreference();
    if (readPref != null)
        rowsCursor.setReadPreference(readPref);

    if (queryProps.getBatchSize() > 0)
        rowsCursor.batchSize(queryProps.getBatchSize());

    if (queryProps.getNumDocsToSkip() > 0)
        rowsCursor.skip(queryProps.getNumDocsToSkip());

    DBObject hintObj = queryProps.getIndexHintsAsParsedObject();
    if (hintObj != null)
        rowsCursor.hint(hintObj);
    else // try to pass the hint string value as is
    {
        String hintValue = queryProps.getIndexHints();
        if (!hintValue.isEmpty())
            rowsCursor.hint(hintValue);
    }

    if (queryProps.hasNoTimeOut())
        rowsCursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
    if (queryProps.isPartialResultsOk())
        rowsCursor.addOption(Bytes.QUERYOPTION_PARTIAL);
}

From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java

License:Apache License

@SuppressWarnings("hiding")
@Override/*from   ww w . j  ava  2  s  .co  m*/
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @SuppressWarnings("unchecked")
        public List doInDB(DB db) throws MongoException, DataAccessException {

            final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
            if (uniqueResult) {
                final DBObject dbObject;
                if (criteria.isEmpty()) {
                    if (entity.isRoot()) {
                        dbObject = collection.findOne();
                    } else {
                        dbObject = collection.findOne(new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator()));
                    }
                } else {
                    dbObject = collection.findOne(getMongoQuery());
                }
                return wrapObjectResultInList(createObjectFromDBObject(dbObject));
            }

            DBCursor cursor = null;
            DBObject query = createQueryObject(entity);

            final List<Projection> projectionList = projections().getProjectionList();
            if (projectionList.isEmpty()) {
                cursor = executeQuery(entity, criteria, collection, query);
                return (List) new MongoResultList(cursor, mongoEntityPersister).clone();
            }

            List projectedResults = new ArrayList();
            for (Projection projection : projectionList) {
                if (projection instanceof CountProjection) {
                    // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
                    //projectedResults.add(collection.getCount(query));
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    projectedResults.add(cursor.size());
                } else if (projection instanceof MinProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MinProjection mp = (MinProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.min((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof MaxProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MaxProjection mp = (MaxProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.max((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof CountDistinctProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    CountDistinctProjection mp = (CountDistinctProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.countDistinct((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));

                } else if ((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
                    final PersistentProperty persistentProperty;
                    final String propertyName;
                    if (projection instanceof IdProjection) {
                        persistentProperty = entity.getIdentity();
                        propertyName = MongoEntityPersister.MONGO_ID_FIELD;
                    } else {
                        PropertyProjection pp = (PropertyProjection) projection;
                        persistentProperty = entity.getPropertyByName(pp.getPropertyName());
                        propertyName = getPropertyName(entity, persistentProperty.getName());
                    }
                    if (persistentProperty != null) {
                        populateMongoQuery(entity, query, criteria);

                        List propertyResults = null;
                        if (max > -1) {
                            // if there is a limit then we have to do a manual projection since the MongoDB driver doesn't support limits and distinct together
                            cursor = executeQueryAndApplyPagination(collection, query);
                            propertyResults = manualProjections
                                    .property(new MongoResultList(cursor, mongoEntityPersister), propertyName);
                        } else {

                            propertyResults = collection.distinct(propertyName, query);
                        }

                        if (persistentProperty instanceof ToOne) {
                            Association a = (Association) persistentProperty;
                            propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(),
                                    propertyResults);
                        }

                        if (projectedResults.size() == 0 && projectionList.size() == 1) {
                            return propertyResults;
                        }
                        projectedResults.add(propertyResults);
                    } else {
                        throw new InvalidDataAccessResourceUsageException(
                                "Cannot use [" + projection.getClass().getSimpleName()
                                        + "] projection on non-existent property: " + propertyName);
                    }
                }
            }

            return projectedResults;
        }

        protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria,
                final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            if (criteria.isEmpty()) {
                cursor = executeQueryAndApplyPagination(collection, query);
            } else {
                populateMongoQuery(entity, query, criteria);
                cursor = executeQueryAndApplyPagination(collection, query);
            }

            if (queryArguments != null) {
                if (queryArguments.containsKey(HINT_ARGUMENT)) {
                    Object hint = queryArguments.get(HINT_ARGUMENT);
                    if (hint instanceof Map) {
                        cursor.hint(new BasicDBObject((Map) hint));
                    } else if (hint != null) {
                        cursor.hint(hint.toString());
                    }

                }
            }
            return cursor;
        }

        protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            cursor = collection.find(query);
            if (offset > 0) {
                cursor.skip(offset);
            }
            if (max > -1) {
                cursor.limit(max);
            }

            if (!orderBy.isEmpty()) {
                DBObject orderObject = new BasicDBObject();
                for (Order order : orderBy) {
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                }
                cursor.sort(orderObject);
            } else {
                MongoCollection coll = (MongoCollection) entity.getMapping().getMappedForm();
                if (coll != null && coll.getSort() != null) {
                    DBObject orderObject = new BasicDBObject();
                    Order order = coll.getSort();
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                    cursor.sort(orderObject);
                }

            }

            return cursor;
        }
    });
}

From source file:org.jongo.Find.java

License:Apache License

public Find hint(String hint) {
    final DBObject hintDBObject = queryFactory.createQuery(hint).toDBObject();
    this.modifiers.add(new QueryModifier() {
        public void modify(DBCursor cursor) {
            cursor.hint(hintDBObject);
        }/*from   w ww . j  a v a2 s .  c o  m*/
    });
    return this;
}