private Document getDocumentById(String collectionId, String id) { if (collection == null) { return null; } // Retrieve the document using the DocumentClient. List<Document> documentList = documentClient .queryDocuments(collection.getSelfLink(), "SELECT * FROM root r WHERE r.id='" + id + "'", feedOptions) .getQueryIterable() .toList(); if (documentList.size() > 0) { return documentList.get(0); } return null; } }
private Database getDatabase() { if (database == null) { // Get the database if it exists List<Database> databaseList = documentClient .queryDatabases( "SELECT * FROM root r WHERE r.id='" + databaseId + "'", null) .getQueryIterable() .toList(); if (databaseList.size() > 0) { // Cache the database object so we won't have to query for it // later to retrieve the selfLink. database = databaseList.get(0); } else { // Create the database if it doesn't exist. try { Database databaseDefinition = new Database(); databaseDefinition.setId(databaseId); database = documentClient.createDatabase(databaseDefinition, null) .getResource(); } catch (DocumentClientException e) { // TODO: Something has gone terribly wrong - the app wasn't // able to query or create the collection. // Verify your connection, endpoint, and key. e.printStackTrace(System.err); } } } return database; }
new SqlParameter("@startkey", startkey))), getFeedOptions(startkey)); documents = feedResponse.getQueryIterable().toList(); } catch (Exception e) { if (!this.includeExceptionStackInLog) {
null) .getQueryIterable() .toList();
private long getCountValue(SqlQuerySpec querySpec, boolean isCrossPartitionQuery, String collectionName) { final FeedResponse<Document> feedResponse = executeQuery(querySpec, isCrossPartitionQuery, collectionName); final Object value = feedResponse.getQueryIterable().toList().get(0).getHashMap().get(COUNT_VALUE_KEY); if (value instanceof Integer) { return Long.valueOf((Integer) value); } else if (value instanceof Long) { return (Long) value; } else { throw new IllegalStateException("Unexpected value type " + value.getClass() + " of value: " + value); } }
/** * Query for aggregation values in a document collection. * * @param collectionLink the link to the parent document collection. * @param querySpec the SQL query specification. * @param feedOptions the feed options. * @param partitionKey the partitionKey. * @return a list containing the aggregation values */ public List<Object> queryAggregateValues(String collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions, Object partitionKey) { List<Document> items = this.queryDocuments(collectionLink, querySpec, feedOptions, partitionKey) .getQueryIterable().toList(); List<Object> values = new ArrayList<>(items.size()); for (Document item : items) { if (item.propertyBag.length() > 0) { values.add(item.propertyBag.get(item.propertyBag.keys().next().toString())); } else { values.add(null); } } return values; }
private <T> List<T> executeQuery(@NonNull SqlQuerySpec sqlQuerySpec, boolean isCrossPartition, @NonNull Class<T> domainClass, String collectionName) { final FeedResponse<Document> feedResponse = executeQuery(sqlQuerySpec, isCrossPartition, collectionName); final List<Document> result = feedResponse.getQueryIterable().toList(); return result.stream().map(r -> getConverter().read(domainClass, r)).collect(Collectors.toList()); }
public <T> List<T> findAll(String collectionName, final Class<T> entityClass) { final List<DocumentCollection> collections = documentDbFactory.getDocumentClient(). queryCollections( getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM ROOT r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (collections.size() != 1) { throw new RuntimeException("expect only one collection: " + collectionName + " in database: " + this.databaseName + ", but found " + collections.size()); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collections.get(0).getSelfLink(), "SELECT * FROM c", null) .getQueryIterable().toList(); final List<T> entities = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final T entity = mappingDocumentDbConverter.read(entityClass, results.get(i)); entities.add(entity); } return entities; }
public <T> List<T> find(Query query, Class<T> domainClass, String collectionName) { final SqlQuerySpec sqlQuerySpec = createSqlQuerySpec(query, domainClass); // TODO (wepa) Collection link should be created locally without accessing database, // but currently exception will be thrown if not fetching collection url from database. // Run repository integration test to reproduce. final DocumentCollection collection = getDocCollection(collectionName); final FeedOptions feedOptions = new FeedOptions(); final Optional<Object> partitionKeyValue = getPartitionKeyValue(query, domainClass); if (!partitionKeyValue.isPresent()) { feedOptions.setEnableCrossPartitionQuery(true); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collection.getSelfLink(), sqlQuerySpec, feedOptions) .getQueryIterable().toList(); final List<T> entities = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final T entity = mappingDocumentDbConverter.read(domainClass, results.get(i)); entities.add(entity); } return entities; }
private DocumentCollection getDocCollection(String collectionName) { final List<DocumentCollection> collections = documentDbFactory.getDocumentClient(). queryCollections( getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM ROOT r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (collections.size() != 1) { throw new IllegalCollectionException("expect only one collection: " + collectionName + " in database: " + this.databaseName + ", but found " + collections.size()); } return collections.get(0); }
public <T> List<T> findAll(String collectionName, final Class<T> entityClass) { final List<DocumentCollection> collections = documentDbFactory.getDocumentClient(). queryCollections( getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM ROOT r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (collections.size() != 1) { throw new IllegalCollectionException("expect only one collection: " + collectionName + " in database: " + this.databaseName + ", but found " + collections.size()); } final FeedOptions feedOptions = new FeedOptions(); feedOptions.setEnableCrossPartitionQuery(true); final SqlQuerySpec sqlQuerySpec = new SqlQuerySpec("SELECT * FROM root c"); final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collections.get(0).getSelfLink(), sqlQuerySpec, feedOptions) .getQueryIterable().toList(); final List<T> entities = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final T entity = mappingDocumentDbConverter.read(entityClass, results.get(i)); entities.add(entity); } return entities; }
private Database createDatabaseIfNotExists(String dbName) { try { final List<Database> dbList = documentDbFactory.getDocumentClient() .queryDatabases(new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", dbName))), null) .getQueryIterable().toList(); if (!dbList.isEmpty()) { return dbList.get(0); } else { // create new database final Database db = new Database(); db.setId(dbName); if (LOGGER.isDebugEnabled()) { LOGGER.debug("execute createDatabase {}", dbName); } final Resource resource = documentDbFactory.getDocumentClient() .createDatabase(db, null).getResource(); if (resource instanceof Database) { return (Database) resource; } else { LOGGER.error("create database {} get unexpected result: {}" + resource.getSelfLink()); throw new RuntimeException("create database {} get unexpected result: " + resource.getSelfLink()); } } } catch (DocumentClientException ex) { throw new RuntimeException("createOrGetDatabase exception", ex); } }
private Database createDatabaseIfNotExists(String dbName) { try { final List<Database> dbList = documentDbFactory.getDocumentClient() .queryDatabases(new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", dbName))), null) .getQueryIterable().toList(); if (!dbList.isEmpty()) { return dbList.get(0); } else { // create new database final Database db = new Database(); db.setId(dbName); if (LOGGER.isDebugEnabled()) { LOGGER.debug("execute createDatabase {}", dbName); } final Resource resource = documentDbFactory.getDocumentClient() .createDatabase(db, null).getResource(); if (resource instanceof Database) { return (Database) resource; } else { final String errorMessage = MessageFormat.format( "create database {0} and get unexpected result: {1}", dbName, resource.getSelfLink()); LOGGER.error(errorMessage); throw new DatabaseCreationException(errorMessage); } } } catch (DocumentClientException ex) { throw new DocumentDBAccessException("createOrGetDatabase exception", ex); } }
@Override public <T> List<T> delete(Query query, Class<T> entityClass, String collectionName) { final SqlQuerySpec sqlQuerySpec = createSqlQuerySpec(query, entityClass); final Optional<Object> partitionKeyValue = getPartitionKeyValue(query, entityClass); final DocumentCollection collection = getDocCollection(collectionName); final FeedOptions feedOptions = new FeedOptions(); if (!partitionKeyValue.isPresent()) { feedOptions.setEnableCrossPartitionQuery(true); } final List<Document> results = documentDbFactory.getDocumentClient() .queryDocuments(collection.getSelfLink(), sqlQuerySpec, feedOptions).getQueryIterable().toList(); final RequestOptions options = new RequestOptions(); if (partitionKeyValue.isPresent()) { options.setPartitionKey(new PartitionKey(partitionKeyValue.get())); } final List<T> deletedResult = new ArrayList<>(); for (final Document document : results) { try { documentDbFactory.getDocumentClient().deleteDocument((document).getSelfLink(), options); deletedResult.add(getConverter().read(entityClass, document)); } catch (DocumentClientException e) { throw new DocumentDBAccessException( String.format("Failed to delete document [%s]", (document).getSelfLink()), e); } } return deletedResult; }
private Database createDatabaseIfNotExists(String dbName) { try { final List<Database> dbList = getDocumentClient() .queryDatabases(new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", dbName))), null) .getQueryIterable().toList(); if (!dbList.isEmpty()) { return dbList.get(0); } else { // create new database final Database db = new Database(); db.setId(dbName); log.debug("execute createDatabase {}", dbName); final Resource resource = getDocumentClient().createDatabase(db, null).getResource(); if (resource instanceof Database) { return (Database) resource; } else { final String errorMessage = MessageFormat.format( "create database {0} and get unexpected result: {1}", dbName, resource.getSelfLink()); log.error(errorMessage); throw new DatabaseCreationException(errorMessage); } } } catch (DocumentClientException ex) { throw new DocumentDBAccessException("createOrGetDatabase exception", ex); } }
public DocumentCollection createCollectionIfNotExists(String collectionName, String partitionKeyFieldName, Integer requestUnit, IndexingPolicy policy) { if (this.databaseCache == null) { this.databaseCache = createDatabaseIfNotExists(this.databaseName); } final List<DocumentCollection> collectionList = documentDbFactory.getDocumentClient() .queryCollections(getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (!collectionList.isEmpty()) { return collectionList.get(0); } else { final RequestOptions requestOptions = getRequestOptions(null, requestUnit); return createCollection(this.databaseName, collectionName, requestOptions, partitionKeyFieldName, policy); } }
private DocumentCollection createCollectionIfNotExists(String dbName, String collectionName) { if (this.databaseCache == null) { this.databaseCache = createDatabaseIfNotExists(dbName); } final List<DocumentCollection> collectionList = documentDbFactory.getDocumentClient() .queryCollections(getDatabaseLink(dbName), new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (!collectionList.isEmpty()) { return collectionList.get(0); } else { final RequestOptions requestOptions = new RequestOptions(); requestOptions.setOfferThroughput(1000); return createCollection(dbName, collectionName, requestOptions); } }
private List<Document> findDocuments(@NonNull DocumentQuery query, @NonNull Class<?> domainClass, @NonNull String collectionName) { final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generate(query); final boolean isCrossPartitionQuery = query.isCrossPartitionQuery(getPartitionKeyNames(domainClass)); final FeedResponse<Document> response = executeQuery(sqlQuerySpec, isCrossPartitionQuery, collectionName); return response.getQueryIterable().toList(); }
@Override public DocumentCollection createCollectionIfNotExists(@NonNull DocumentDbEntityInformation information) { if (this.databaseCache == null) { this.databaseCache = createDatabaseIfNotExists(this.databaseName); } final String collectionName = information.getCollectionName(); final String partitionKeyFieldName = information.getPartitionKeyFieldName(); final List<DocumentCollection> collectionList = getDocumentClient() .queryCollections(getDatabaseLink(this.databaseName), new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionName))), null) .getQueryIterable().toList(); if (!collectionList.isEmpty()) { return collectionList.get(0); } else { return createCollection(this.databaseName, partitionKeyFieldName, information); } }
partitionKeyRanges = this.readPartitionKeyRanges(collectionLink, (FeedOptions) null).getQueryIterable().toList();