Get a collection (Java)
Gets a reference to a collection for use with the Data API clients.
|
Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart. |
Result
Returns a Collection<T> object that corresponds to the specified collection name.
This method returns a Collection<T> object even for collections that don’t exist.
A Collection is typed as Collection<T>, where T defaults to Document which can be seen as a generic map of String to Object.
Providing the specific T type enables stronger typing for collection operations. (eg: Collecion<MyBean>)
For more information see the client reference.
Signature
Use the getCollection method, which belongs to the com.datastax.astra.client.Database class.
Collection<Document> getCollection(String collectionName)
Collection<Document> getCollection(
String collectionName,
CollectionOptions options
)
<T> Collection<T> getCollection(
String collectionName,
Class<T> documentClass
)
<T> Collection<T> getCollection(
String collectionName,
Class<T> documentClass
CollectionOptions options,
)
Parameters
| Name | Type | Summary |
|---|---|---|
|
|
The name of the collection. |
|
Optional.
The options for this operation.
See Selected methods of |
| Method | Parameters | Summary |
|---|---|---|
|
|
Optional if you specified a working keyspace when you created the Default: The working keyspace set when you created the |
|
|
Optional.
A timeout, in milliseconds, for the underlying HTTP request.
If not provided, the |
Examples
The following examples demonstrate how to get a collection.
Get a collection
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.databases.Database;
public class Example {
public static void main(String[] args) {
// Get a database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
// Get a collection
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
}
}
Errors
For a full list of Data API error codes and their corresponding messages, see Data API errors and error codes.
For more information about how the client handles underlying Data API errors, see Java client error handling.
Client reference
For more information, see the client reference.