Astra DB Serverless quickstart for tables (Java)
|
If your data is not fully structured, or if you do not want to use a fixed schema, see the quickstart for collections instead. This quickstart requires a Serverless (vector) database. For Serverless (non-vector) databases, see Get started with the Data API (Java). |
This quickstart demonstrates how to create a table schema, insert data to a table, generate vector embeddings, and perform a vector search to find similar data.
The Next steps section discusses how to insert other types of data, use a different embedding model, insert data with pre-generated vector embeddings, or skip embedding generation.
To learn more about vector databases and vector search, see What are vector databases? and What is Vector Search.
Create a database and store your credentials
-
Click Create database.
-
For this quickstart, select the following:
-
Type: Serverless (vector)
-
Provider: Amazon Web Services
-
Region: us-east-2
-
-
If applicable to your organization, you can select or create a PCU group for the database.
-
Click Create database.
Wait for your database to initialize and reach Active status. This can take several minutes.
-
Under Database Details, copy your database’s API endpoint.
-
Under Database Details, click Generate Token, then copy the token.
-
For this quickstart, store the endpoint and token in environment variables:
-
Linux or macOS
-
Windows
export API_ENDPOINT=API_ENDPOINT export APPLICATION_TOKEN=APPLICATION_TOKENset API_ENDPOINT=API_ENDPOINTset APPLICATION_TOKEN=APPLICATION_TOKEN -
Install a client
Install one of the Data API clients to facilitate interactions with the Data API. To use the Data API with tables, you must install client version 2.0.x.
-
Maven
-
Gradle
-
Update to Java version 17 or later if needed. DataStax recommends Java 21.
-
Update to Apache Maven™ version 3.9 or later if needed.
-
Add a dependency to the latest version of the astra-db-java package.
pom.xml<dependencies> <dependency> <groupId>com.datastax.astra</groupId> <artifactId>astra-db-java</artifactId> <version>VERSION</version> </dependency> </dependencies>
-
Update to Java version 17 or later if needed. DataStax recommends Java 21.
-
Update to Gradle version 11 or later if needed.
-
Add a dependency to the latest version of the astra-db-java package.
build.gradle(.kts)dependencies { implementation 'com.datastax.astra:astra-db-java:VERSION' }
To test pre-generated commands without installing a client, you can use the Data API console in the Astra Portal. The scripts used in this quickstart aren’t compatible with the Data API console because they are intended for use with a Data API client.
Connect to your database
The following function will connect to your database.
Copy the file into your project. You don’t need to execute the function now; the subsequent code examples will import and use this function.
package com.quickstart;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.databases.Database;
public class QuickstartConnect {
/**
* Connects to a DataStax Astra database. This function retrieves the database endpoint and
* application token from the environment variables `API_ENDPOINT` and `APPLICATION_TOKEN`.
*
* @return an instance of the connected database
* @throws IllegalStateException if the environment variables `API_ENDPOINT` or
* `APPLICATION_TOKEN` are not defined
*/
public static Database connectToDatabase() {
String endpoint = System.getenv("API_ENDPOINT"); (1)
String token = System.getenv("APPLICATION_TOKEN");
if (endpoint == null || token == null) {
throw new IllegalStateException(
"Environment variables API_ENDPOINT and APPLICATION_TOKEN must be defined");
}
// Create an instance of `DataAPIClient` with your token.
DataAPIClient client = new DataAPIClient(token);
// Get the database specified by your endpoint.
Database database = client.getDatabase(endpoint);
System.out.println("Connected to database.");
return database;
}
}
| 1 | Store your database’s endpoint and application token in environment variables named API_ENDPOINT and APPLICATION_TOKEN, as instructed in Create a database and store your credentials. |
Create a table
The following code will create an empty table in your database. The table created here matches the structure of the data that you will insert to the table. After creating the table, the code will index some columns so that you can find and sort data in those columns.
-
Copy the code into your project.
-
If needed, update the import path to the "connect to database" function from the previous section.
-
Execute the code.
For information about executing code, refer to the documentation for your programming language.
Once the code completes, you should see a printed message confirming the table creation.
package com.quickstart;
import com.datastax.astra.client.core.vector.SimilarityMetric;
import com.datastax.astra.client.core.vectorize.VectorServiceOptions;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnDefinitionVector;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.indexes.TableVectorIndexDefinition;
import com.datastax.astra.client.tables.definition.rows.Row;
public class QuickstartTableCreateDemo {
public static void main(String[] args) {
Database database = QuickstartConnect.connectToDatabase(); (1)
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnText("title")
.addColumnText("author")
.addColumnInt("number_of_pages")
.addColumn("rating", TableColumnTypes.FLOAT)
.addColumnInt("publication_year")
.addColumnText("summary")
.addColumnSet("genres", TableColumnTypes.TEXT)
.addColumnMap("metadata", TableColumnTypes.TEXT, TableColumnTypes.TEXT)
.addColumnBoolean("is_checked_out")
.addColumnText("borrower")
.addColumn("due_date", TableColumnTypes.DATE)
// This column will store vector embeddings.
// The column will use an embedding model from NVIDIA to generate the
// vector embeddings when data is inserted to the column. (2)
.addColumnVector(
"summary_genres_vector",
new TableColumnDefinitionVector()
.dimension(1024)
.service(
new VectorServiceOptions()
.provider("nvidia")
.modelName("nvidia/nv-embedqa-e5-v5")))
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
.addPartitionBy("title")
.addPartitionBy("author");
// Default Table Creation
Table<Row> table =
database.createTable(
"quickstart_table", (3)
tableDefinition);
System.out.println("Created table.");
// Index any columns that you want to sort and filter on.
table.createIndex("rating_index", "rating");
table.createIndex("number_of_pages_index", "number_of_pages");
TableVectorIndexDefinition definition =
new TableVectorIndexDefinition()
.column("summary_genres_vector")
.metric(SimilarityMetric.COSINE);
table.createVectorIndex("summary_genres_vector_index", definition);
System.out.println("Indexed columns.");
}
}
| 1 | This is the connectToDatabase function from the previous section. Update the import path if necessary.
To use the function, ensure you stored your database’s endpoint and application token in environment variables as instructed in Create a database and store your credentials. |
| 2 | This column will use the Astra-hosted NVIDIA embedding model to generate vector embeddings. This is currently only supported in certain regions. Ensure that your database is in the Amazon Web Services us-east-2 region, as instructed in Create a database and store your credentials. |
| 3 | This code creates a table named quickstart_table. If you want to use a different name, change the name before running the code. |
Insert data to your table
The following code will insert data from a JSON file into a your table.
-
Copy the code into your project.
-
Download the quickstart_dataset.json sample dataset (76 kB). This dataset is a JSON array describing library books.
-
Replace
PATH_TO_DATA_FILEin the code with the path to the dataset. -
If needed, update the import path to the "connect to database" function from the previous section.
-
Execute the code.
For information about executing code, refer to the documentation for your programming language.
Once the code completes, you should see a printed message confirming the insertion of 100 rows.
package com.quickstart;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.results.TableInsertManyResult;
import com.datastax.astra.client.tables.definition.rows.Row;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class QuickstartInsertToTableDemo {
private static Date parseDate(String date) {
if (date == null) return null;
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
Database database = QuickstartConnect.connectToDatabase(); (1)
Table<Row> table = database.getTable("quickstart_table"); (2)
// Initialize Jackson ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
try (FileInputStream stream = new FileInputStream("PATH_TO_DATA_FILE")) { (3)
List<Row> rows = objectMapper.readValue(stream, new TypeReference<>() {});
rows.forEach(
row -> {
// Deserialize the "genres" field into a HashSet
row.add("genres", new HashSet<>(row.getList("genres", String.class)));
// Deserialize the "metadata" field into a Map
Map<String, String> metadataMap =
objectMapper.convertValue(
row.get("metadata"), new TypeReference<Map<String, String>>() {});
row.add("metadata", metadataMap);
// Deserialize the "due_date" field into a Date or null
row.add("due_date", parseDate(row.getText("due_date")));
// Add a field of text to vectorize
String summary = row.getText("summary");
String genres = String.join(", ", row.getList("genres", String.class));
String summary_genres_vector =
String.format("summary: %s | genres: %s", summary, genres);
row.add("summary_genres_vector", summary_genres_vector);
});
TableInsertManyResult result = table.insertMany(rows);
System.out.println("Inserted " + result.getInsertedIds().size() + " items.");
}
}
}
| 1 | This is the connectToDatabase function from the previous section.
To use the function, ensure you stored your database’s endpoint and application token in environment variables as instructed in Create a database and store your credentials. |
| 2 | If you changed the table name in the previous code, change it in this code as well. |
| 3 | Replace PATH_TO_DATA_FILE with the path to the JSON data file. |
Find data in your table
After you insert data to your table, you can search the data. In addition to traditional database filtering, you can perform a vector search to find data that is most similar to a search string.
The following code performs three searches on the sample data that you loaded in Insert data to your table.
package com.quickstart;
import static com.datastax.astra.client.core.query.Projection.include;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.commands.options.TableFindOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
public class QuickstartFindTableRowsDemo {
public static void main(String[] args) {
Database database = QuickstartConnect.connectToDatabase(); (1)
Table<Row> table = database.getTable("quickstart_table"); (2)
// Find rows that match a filter
System.out.println("\nFinding books with rating greater than 4.7...");
Filter filter = Filters.gt("rating", 4.7);
TableFindOptions options =
new TableFindOptions().limit(10).projection(include("title", "rating"));
table
.find(filter, options)
.forEach(
row -> {
System.out.println(row.get("title") + " is rated " + row.get("rating"));
});
// Perform a vector search to find the closest match to a search string
System.out.println("\nUsing vector search to find a single scary novel...");
TableFindOneOptions options2 =
new TableFindOneOptions()
.sort(Sort.vectorize("summary_genres_vector", "A scary novel"))
.projection(include("title"));
table
.findOne(options2)
.ifPresent(
row -> {
System.out.println(row.get("title") + " is a scary novel");
});
// Combine a filter, vector search, and projection to find the 3 books with
// more than 400 pages that are the closest matches to a search string
System.out.println(
"\nUsing filters and vector search to find 3 books with more than 400 pages that are set in the arctic, returning just the title and author...");
Filter filter3 = Filters.gt("number_of_pages", 400);
TableFindOptions options3 =
new TableFindOptions()
.limit(3)
.sort(Sort.vectorize("summary_genres_vector", "A book set in the arctic"))
.projection(include("title", "author"));
table
.find(filter3, options3)
.forEach(
row -> {
System.out.println(row);
});
}
}
| 1 | This is the connectToDatabase function from the previous section. |
| 2 | If you changed the table name in the previous code, change it in this code as well. |
Next steps
For more practice, you can continue building with the table that you created here. For example, try inserting more data to the table, or try different searches. The Data API reference provides code examples for various operations.
- Insert data from different sources
-
This quickstart demonstrated how to insert structured data from a JSON file into a table, but you can insert data from many sources.
Tables use fixed schemas. If your data is unstructured or if you want a flexible schema, you can use a collection instead of a table. See the quickstart for collections.
- Use a different method to generate vector embeddings
-
This quickstart used the Astra-hosted NVIDIA embedding model to generate vector embeddings. You can also use other embedding models, or you can insert data with pre-generated vector embeddings (or without vector embeddings) and skip embedding.
-
To use a different embedding model, see Generate and store embeddings in Astra DB Serverless databases and Work with rows: Vector type.
-
To insert pre-embedded data, you need to specify the vector dimensions and similarity metric instead of specifying the embedding provider. See Work with rows: Vector type.
-
- Perform more complex searches
-
This quickstart demonstrated how to find data using filters and vector search. To learn more about the searches you can perform, see Ways to find data in Astra DB Serverless.
- Use different database settings
-
For this quickstart, you need a Serverless (vector) database in the Amazon Web Services us-east-2 region, which is required for the Astra-hosted NVIDIA embedding model integration. For production databases, you might use different database settings. For more information, see Astra DB Serverless database regions and maintenance schedules and Create an Astra DB Serverless database.