Search code examples
azure-cosmosdbazure-cosmosdb-sqlapiazure-sdkazure-sdk-for-java

Azure CosmosDB Java Delete All items in a Container


I'm trying to delete all items in a CosmosDB container -- I cannot delete the container. I cannot find an efficient way to do this.

I have a related problem where I am trying to select all/read all so I can get their id in order to then call a delete on them all...bearing in mind this is probably incredibly inefficient. Modifying the published example very slightly i am trying to select all documents as below:

private void queryDocuments() throws Exception {
logger.info("Query documents in the container " + containerName + ".");

String sql = "SELECT * FROM c";

CosmosPagedIterable<Family> filteredFamilies = container.queryItems(sql, new
CosmosQueryRequestOptions(), Family.class);


while (filteredFamilies.iterator().hasNext()) {
Family family = filteredFamilies.iterator().next();
logger.info("First query result: Family with (/id, partition key) =
(%s,%s)",family.getId(),family.getLastName());
}

logger.info("Done.");
}

The code above only retrieves 1 document and the while loop iterates forever printing out the same document. I have 2 questions:

  1. How can i fix the above query to operate like a typical SELECT ALL
  2. Is there a better way to delete all items in a container via Java SDK without deleting the container?

Solution

  • You can try setting TTL for your container to 10secs or something. If no new record is created or updated this will automatically delete all items. https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/time-to-live