List of usage examples for com.mongodb QueryBuilder get
public DBObject get()
From source file:org.apache.gora.mongodb.filters.DefaultFactory.java
License:Apache License
protected DBObject transformFieldFilter(final SingleFieldValueFilter<K, T> fieldFilter, final MongoStore<K, T> store) { MongoMapping mapping = store.getMapping(); String dbFieldName = mapping.getDocumentField(fieldFilter.getFieldName()); FilterOp filterOp = fieldFilter.getFilterOp(); List<Object> operands = fieldFilter.getOperands(); QueryBuilder builder = QueryBuilder.start(dbFieldName); builder = appendToBuilder(builder, filterOp, operands); if (!fieldFilter.isFilterIfMissing()) { // If false, the find query will pass if the column is not found. DBObject notExist = QueryBuilder.start(dbFieldName).exists(false).get(); builder = QueryBuilder.start().or(notExist, builder.get()); }/* ww w . j a v a 2 s. c om*/ return builder.get(); }
From source file:org.apache.gora.mongodb.filters.DefaultFactory.java
License:Apache License
protected DBObject transformMapFilter(final MapFieldValueFilter<K, T> mapFilter, final MongoStore<K, T> store) { MongoMapping mapping = store.getMapping(); String dbFieldName = mapping.getDocumentField(mapFilter.getFieldName()) + "." + store.encodeFieldKey(mapFilter.getMapKey().toString()); FilterOp filterOp = mapFilter.getFilterOp(); List<Object> operands = mapFilter.getOperands(); QueryBuilder builder = QueryBuilder.start(dbFieldName); builder = appendToBuilder(builder, filterOp, operands); if (!mapFilter.isFilterIfMissing()) { // If false, the find query will pass if the column is not found. DBObject notExist = QueryBuilder.start(dbFieldName).exists(false).get(); builder = QueryBuilder.start().or(notExist, builder.get()); }/*from w ww.j a v a 2 s . c o m*/ return builder.get(); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java
License:Apache License
private static DBObject getBlobQuery(String id, long lastMod) { QueryBuilder queryBuilder = new QueryBuilder(); if (id != null) { queryBuilder = queryBuilder.and(MongoBlob.KEY_ID).is(id); }//from w w w .j av a 2 s . c o m if (lastMod > 0) { queryBuilder = queryBuilder.and(MongoBlob.KEY_LAST_MOD).lessThan(lastMod); } return queryBuilder.get(); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java
License:Apache License
@Override public long countDeleteChunks(List<String> chunkIds, long maxLastModifiedTime) throws Exception { DBCollection collection = getBlobCollection(); QueryBuilder queryBuilder = new QueryBuilder(); if (chunkIds != null) { queryBuilder = queryBuilder.and(MongoBlob.KEY_ID).in(chunkIds.toArray(new String[0])); if (maxLastModifiedTime > 0) { queryBuilder = queryBuilder.and(MongoBlob.KEY_LAST_MOD).lessThan(maxLastModifiedTime); }/*from w ww . j a v a 2s . c o m*/ } WriteResult result = collection.remove(queryBuilder.get()); return result.getN(); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java
License:Apache License
@Override public Iterator<String> getAllChunkIds(long maxLastModifiedTime) throws Exception { DBCollection collection = getBlobCollection(); DBObject fields = new BasicDBObject(); fields.put(MongoBlob.KEY_ID, 1);//from w ww.ja v a 2 s . c o m QueryBuilder builder = new QueryBuilder(); if (maxLastModifiedTime != 0 && maxLastModifiedTime != -1) { builder.and(MongoBlob.KEY_LAST_MOD).lessThanEquals(maxLastModifiedTime); } final DBCursor cur = collection.find(builder.get(), fields).hint(fields) .addOption(Bytes.QUERYOPTION_SLAVEOK); //TODO The cursor needs to be closed return new AbstractIterator<String>() { @Override protected String computeNext() { if (cur.hasNext()) { MongoBlob blob = (MongoBlob) cur.next(); if (blob != null) { return blob.getId(); } } return endOfData(); } }; }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java
License:Apache License
@SuppressWarnings("unchecked") @Nonnull/*w ww . ja v a 2 s. c o 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.MongoDocumentStore.java
License:Apache License
@Override public <T extends Document> int remove(Collection<T> collection, Map<String, Map<Key, Condition>> toRemove) { log("remove", toRemove); int num = 0;//from w w w .j a va 2 s. c om DBCollection dbCollection = getDBCollection(collection); long start = PERFLOG.start(); try { List<String> batchIds = Lists.newArrayList(); List<DBObject> batch = Lists.newArrayList(); Iterator<Entry<String, Map<Key, Condition>>> it = toRemove.entrySet().iterator(); while (it.hasNext()) { Entry<String, Map<Key, Condition>> entry = it.next(); QueryBuilder query = createQueryForUpdate(entry.getKey(), entry.getValue()); batchIds.add(entry.getKey()); batch.add(query.get()); if (!it.hasNext() || batch.size() == IN_CLAUSE_BATCH_SIZE) { DBObject q = new BasicDBObject(); q.put(QueryOperators.OR, batch); try { num += dbCollection.remove(q).getN(); } catch (Exception e) { throw DocumentStoreException.convert(e, "Remove failed for " + batch); } finally { if (collection == Collection.NODES) { invalidateCache(batchIds); } } batchIds.clear(); batch.clear(); } } } finally { PERFLOG.end(start, 1, "remove keys={}", toRemove); } return num; }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java
License:Apache License
@SuppressWarnings("unchecked") @CheckForNull// w w w . ja v a 2s.c om private <T extends Document> T findAndModify(Collection<T> collection, UpdateOp updateOp, boolean upsert, boolean checkConditions) { DBCollection dbCollection = getDBCollection(collection); // make sure we don't modify the original updateOp updateOp = updateOp.copy(); DBObject update = createUpdate(updateOp, false); Lock lock = null; if (collection == Collection.NODES) { lock = nodeLocks.acquire(updateOp.getId()); } final Stopwatch watch = startWatch(); boolean newEntry = false; try { // get modCount of cached document Long modCount = null; T cachedDoc = null; if (collection == Collection.NODES) { cachedDoc = (T) nodesCache.getIfPresent(updateOp.getId()); if (cachedDoc != null) { modCount = cachedDoc.getModCount(); } } // perform a conditional update with limited result // if we have a matching modCount if (modCount != null) { QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); query.and(Document.MOD_COUNT).is(modCount); WriteResult result = dbCollection.update(query.get(), update); if (result.getN() > 0) { // success, update cached document if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, cachedDoc, updateOp); nodesCache.put(newDoc); } // return previously cached document return cachedDoc; } } // conditional update failed or not possible // perform operation and get complete document QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); DBObject oldNode = dbCollection.findAndModify(query.get(), null, null /*sort*/, false /*remove*/, update, false /*returnNew*/, upsert); if (oldNode == null) { newEntry = true; } if (checkConditions && oldNode == null) { return null; } T oldDoc = convertFromDBObject(collection, oldNode); if (oldDoc != null) { if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, oldDoc, updateOp); nodesCache.put(newDoc); updateLocalChanges(newDoc); } oldDoc.seal(); } else if (upsert) { if (collection == Collection.NODES) { NodeDocument doc = (NodeDocument) collection.newDocument(this); UpdateUtils.applyChanges(doc, updateOp); nodesCache.putIfAbsent(doc); updateLocalChanges(doc); } } else { // updateOp without conditions and not an upsert // this means the document does not exist } return oldDoc; } catch (Exception e) { throw DocumentStoreException.convert(e); } finally { if (lock != null) { lock.unlock(); } stats.doneFindAndModify(watch.elapsed(TimeUnit.NANOSECONDS), collection, updateOp.getId(), newEntry, true, 0); } }
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 w w w . jav a 2s . com*/ 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.MongoDocumentStore.java
License:Apache License
private <T extends Document> BulkUpdateResult sendBulkUpdate(Collection<T> collection, java.util.Collection<UpdateOp> updateOps, Map<String, T> oldDocs) { DBCollection dbCollection = getDBCollection(collection); BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation(); String[] bulkIds = new String[updateOps.size()]; int i = 0;/*from w ww. j a va 2 s . c o m*/ for (UpdateOp updateOp : updateOps) { String id = updateOp.getId(); QueryBuilder query = createQueryForUpdate(id, updateOp.getConditions()); T oldDoc = oldDocs.get(id); DBObject update; if (oldDoc == null) { query.and(Document.MOD_COUNT).exists(false); update = createUpdate(updateOp, true); } else { query.and(Document.MOD_COUNT).is(oldDoc.getModCount()); update = createUpdate(updateOp, false); } bulk.find(query.get()).upsert().updateOne(update); bulkIds[i++] = id; } BulkWriteResult bulkResult; Set<String> failedUpdates = new HashSet<String>(); Set<String> upserts = new HashSet<String>(); try { bulkResult = bulk.execute(); } catch (BulkWriteException e) { bulkResult = e.getWriteResult(); for (BulkWriteError err : e.getWriteErrors()) { failedUpdates.add(bulkIds[err.getIndex()]); } } for (BulkWriteUpsert upsert : bulkResult.getUpserts()) { upserts.add(bulkIds[upsert.getIndex()]); } return new BulkUpdateResult(failedUpdates, upserts); }