Couchbase : List available Buckets, scopes and collection available in a Cluster with Java SDK 3

Viewed 450

Working on a Java application I would like to list all available buckets / scopes and collections available for choice by the user. This is written using Couchbase Java SDK 3.0

I did not find any resources on the web.

Many thanks,

1 Answers

Cluster has a buckets() method that returns a BucketManager. You can use this manager to get a map of bucket names to bucket info. If you want only the names, grab them from this map's keyset.

To access scope/collection info, first get a Bucket from the Cluster. The you can call the bucket's collections() method to get the bucket's CollectionManager. From there you can get all the scopes, and query each scope to find out which collections it contains.

Cluster cluster = Cluster.connect("localhost", "Administrator", "password");
cluster.waitUntilReady(Duration.ofSeconds(10));

BucketManager bucketManager = cluster.buckets();
Set<String> bucketNames = bucketManager.getAllBuckets().keySet();

for (String bucketName : bucketNames) {
  Bucket bucket = cluster.bucket(bucketName);
  System.out.println("Bucket: " + bucketName);

  CollectionManager collectionManager = bucket.collections();
  for (ScopeSpec scope : collectionManager.getAllScopes()) {
    System.out.println("  Scope: " + scope.name());

    for (CollectionSpec collection : scope.collections()) {
      System.out.println("    Collection: " + collection.name());
    }
  }
}

This code throws FeatureNotAvailableException if the server does not support collections.

Related