package astra
import "github.com/datastax/astra-db-go/v2/astra"
Package astra implements the astra database client.
Index
- Constants
- Variables
- func EscapeFieldNames(segments ...any) string
- func NewDocumentTargetCtx() serdes.TargetDecodeCtx
- func NewRowTargetCtx(cols table.Columns) serdes.TargetDecodeCtx
- func UnescapeFieldPath(path string) ([]string, error)
-
type AstraAdmin
- func (a *AstraAdmin) ClientOptions() *options.APIOptions
- func (a *AstraAdmin) CreateDatabase(ctx context.Context, params CreateDatabaseParams, ...) (*AstraDatabaseAdmin, error)
- func (a *AstraAdmin) DatabaseAdmin(id, region string, opts ...options.APIOption) *AstraDatabaseAdmin
- func (a *AstraAdmin) DatabaseAdminFromEndpoint(endpoint string, opts ...options.APIOption) *AstraDatabaseAdmin
- func (a *AstraAdmin) DatabaseInfo(ctx context.Context, databaseID string, opts ...options.DatabaseInfoOption) (*FullAstraDatabaseInfo, error)
- func (a *AstraAdmin) DropDatabase(ctx context.Context, databaseID string, opts ...options.DropDatabaseOption) error
- func (a *AstraAdmin) FindAvailableRegions(ctx context.Context, opts ...options.FindAvailableRegionsOption) ([]Region, error)
- func (a *AstraAdmin) ListDatabases(ctx context.Context, opts ...options.ListDatabasesOption) ([]FullAstraDatabaseInfo, error)
-
type AstraDatabaseAdmin
- func (a *AstraDatabaseAdmin) CreateKeyspace(ctx context.Context, keyspace string, opts ...options.CreateKeyspaceOption) error
- func (a *AstraDatabaseAdmin) Db() *Db
- func (a *AstraDatabaseAdmin) Drop(ctx context.Context, opts ...options.DropDatabaseOption) error
- func (a *AstraDatabaseAdmin) DropKeyspace(ctx context.Context, keyspace string, opts ...options.DropKeyspaceOption) error
- func (a *AstraDatabaseAdmin) FindEmbeddingProviders(ctx context.Context, opts ...options.FindEmbeddingProvidersOption) (*results.FindEmbeddingProvidersResult, error)
- func (a *AstraDatabaseAdmin) ID() string
- func (a *AstraDatabaseAdmin) Info(ctx context.Context, opts ...options.DatabaseInfoOption) (*FullAstraDatabaseInfo, error)
- func (a *AstraDatabaseAdmin) ListKeyspaces(ctx context.Context, opts ...options.ListKeyspacesOption) ([]string, error)
- type AstraDatabaseRegionInfo
- type AwaitStatusOptions
- type BaseAstraDatabaseInfo
-
type Collection
- func (c *Collection) ClientOptions() *options.APIOptions
- func (c *Collection) CountDocuments(ctx context.Context, f CollectionFilter, upperBound int, ...) (int, error)
- func (c *Collection) Database() *Db
- func (c *Collection) DeleteMany(ctx context.Context, f CollectionFilter, ...) (*results.DeleteResult, error)
- func (c *Collection) DeleteOne(ctx context.Context, f CollectionFilter, ...) (*results.DeleteResult, error)
- func (c *Collection) Drop(ctx context.Context, opts ...options.DropCollectionOption) error
- func (c *Collection) EstimatedDocumentCount(ctx context.Context, opts ...options.CollectionEstimatedDocumentCountOption) (int, error)
- func (c *Collection) Find(f CollectionFilter, opts ...options.CollectionFindOption) *cursors.CollectionFindCursor
- func (c *Collection) FindAndRerank(f CollectionFilter, opts ...options.CollectionFindAndRerankOption) cursors.FindAndRerankCursor
- func (c *Collection) FindOne(ctx context.Context, f CollectionFilter, ...) *results.SingleResult
- func (c *Collection) FindOneAndDelete(ctx context.Context, f CollectionFilter, ...) *results.SingleResult
- func (c *Collection) FindOneAndReplace(ctx context.Context, f CollectionFilter, replacement any, ...) *results.SingleResult
- func (c *Collection) FindOneAndUpdate(ctx context.Context, f CollectionFilter, u CollectionUpdate, ...) *results.SingleResult
- func (c *Collection) InsertMany(ctx context.Context, documents any, opts ...options.CollectionInsertManyOption) (*results.InsertManyResult, error)
- func (c *Collection) InsertOne(ctx context.Context, document any, opts ...options.CollectionInsertOneOption) (*results.InsertOneResult, error)
- func (c *Collection) Name() string
- func (c *Collection) Options(ctx context.Context, opts ...options.CollectionOptionsOption) (*results.CollectionDescriptor, error)
- func (c *Collection) ReplaceOne(ctx context.Context, f CollectionFilter, replacement any, ...) (*results.UpdateResult, error)
- func (c *Collection) UpdateMany(ctx context.Context, f CollectionFilter, u CollectionUpdate, ...) (*results.UpdateResult, error)
- func (c *Collection) UpdateOne(ctx context.Context, f CollectionFilter, u CollectionUpdate, ...) (*results.UpdateResult, error)
- type CollectionFilter
- type CollectionUpdate
- type CreateDatabaseParams
- type DataAPIClient
-
type DataAPIDatabaseAdmin
- func (a *DataAPIDatabaseAdmin) CreateKeyspace(ctx context.Context, keyspace string, opts ...options.CreateKeyspaceOption) error
- func (a *DataAPIDatabaseAdmin) DropKeyspace(ctx context.Context, keyspace string, opts ...options.DropKeyspaceOption) error
- func (a *DataAPIDatabaseAdmin) FindEmbeddingProviders(ctx context.Context, opts ...options.FindEmbeddingProvidersOption) (*results.FindEmbeddingProvidersResult, error)
- func (a *DataAPIDatabaseAdmin) ListKeyspaces(ctx context.Context, opts ...options.ListKeyspacesOption) ([]string, error)
- type DatabaseAdmin
- type DatabaseStatus
-
type Db
- func (d *Db) AlterType(ctx context.Context, name string, op table.AlterTypeOperation, ...) error
- func (d *Db) Client() *DataAPIClient
- func (d *Db) ClientOptions() *options.APIOptions
- func (d *Db) Collection(name string, opts ...options.GetCollectionOption) *Collection
- func (d *Db) CreateCollection(ctx context.Context, name string, opts ...options.CreateCollectionOption) (*Collection, error)
- func (d *Db) CreateTable(ctx context.Context, name string, definition table.Definition, ...) (*Table, error)
- func (d *Db) CreateType(ctx context.Context, name string, definition table.UDTDefinition, ...) error
- func (d *Db) DatabaseAdmin() (DatabaseAdmin, error)
- func (d *Db) DropCollection(ctx context.Context, name string, opts ...options.DropCollectionOption) error
- func (d *Db) DropTable(ctx context.Context, name string, opts ...options.DropTableOption) error
- func (d *Db) DropTableIndex(ctx context.Context, name string, opts ...options.DropTableIndexOption) error
- func (d *Db) DropType(ctx context.Context, name string, opts ...options.DropTypeOption) error
- func (d *Db) Endpoint() string
- func (d *Db) ID() (string, error)
- func (d *Db) Info(ctx context.Context, opts ...options.DatabaseInfoOption) (*PartialAstraDatabaseInfo, error)
- func (d *Db) ListCollectionNames(ctx context.Context, opts ...options.ListCollectionsOption) ([]string, error)
- func (d *Db) ListCollections(ctx context.Context, opts ...options.ListCollectionsOption) ([]results.CollectionDescriptor, error)
- func (d *Db) ListTableNames(ctx context.Context, opts ...options.ListTablesOption) ([]string, error)
- func (d *Db) ListTables(ctx context.Context, opts ...options.ListTablesOption) ([]results.TableDescriptor, error)
- func (d *Db) ListTypeNames(ctx context.Context, opts ...options.ListTypesOption) ([]string, error)
- func (d *Db) ListTypes(ctx context.Context, opts ...options.ListTypesOption) ([]results.UDTDescriptor, error)
- func (d *Db) Region() (string, error)
- func (d *Db) Table(name string, opts ...options.GetTableOption) *Table
- func (d *Db) UseKeyspace(keyspace string)
- type Document
- type FullAstraDatabaseInfo
- type NewDocument
- type NewRow
- type PartialAstraDatabaseInfo
- type Region
- type Row
-
type Table
- func (t *Table) Alter(ctx context.Context, op table.AlterOperation, opts ...options.AlterTableOption) error
- func (t *Table) ClientOptions() *options.APIOptions
- func (t *Table) CreateIndex(ctx context.Context, name string, column any, ...) error
- func (t *Table) CreateTextIndex(ctx context.Context, name string, column string, ...) error
- func (t *Table) CreateVectorIndex(ctx context.Context, name string, column string, ...) error
- func (t *Table) Database() *Db
- func (t *Table) Definition(ctx context.Context, opts ...options.TableDefinitionOption) (*results.TableDescriptor, error)
- func (t *Table) DeleteMany(ctx context.Context, f TableFilter, opts ...options.TableDeleteManyOption) error
- func (t *Table) DeleteOne(ctx context.Context, f TableFilter, opts ...options.TableDeleteOneOption) error
- func (t *Table) Drop(ctx context.Context, opts ...options.DropTableOption) error
- func (t *Table) Find(f TableFilter, opts ...options.TableFindOption) *cursors.TableFindCursor
- func (t *Table) FindOne(ctx context.Context, f TableFilter, opts ...options.TableFindOneOption) *results.SingleResult
- func (t *Table) InsertMany(ctx context.Context, rows any, opts ...options.TableInsertManyOption) (*results.InsertManyResult, error)
- func (t *Table) InsertOne(ctx context.Context, row any, opts ...options.TableInsertOneOption) (*results.InsertOneResult, error)
- func (t *Table) ListIndexNames(ctx context.Context, opts ...options.ListIndexesOption) ([]string, error)
- func (t *Table) ListIndexes(ctx context.Context, opts ...options.ListIndexesOption) ([]results.IndexDescriptor, error)
- func (t *Table) Name() string
- func (t *Table) UpdateOne(ctx context.Context, f TableFilter, u TableUpdate, ...) error
- type TableFilter
- type TableUpdate
- type WithSimilarity
Examples
Constants
const ( DatabaseStatusActive = options.DatabaseStatusActive DatabaseStatusAssociating = options.DatabaseStatusAssociating DatabaseStatusPending = options.DatabaseStatusPending DatabaseStatusInitializing = options.DatabaseStatusInitializing DatabaseStatusTerminating = options.DatabaseStatusTerminating DatabaseStatusTerminated = options.DatabaseStatusTerminated DatabaseStatusMaintenance = options.DatabaseStatusMaintenance DatabaseStatusError = options.DatabaseStatusError DatabaseStatusParking = options.DatabaseStatusParking DatabaseStatusParked = options.DatabaseStatusParked DatabaseStatusUnparking = options.DatabaseStatusUnparking DatabaseStatusPreparing = options.DatabaseStatusPreparing DatabaseStatusPrepared = options.DatabaseStatusPrepared DatabaseStatusResizing = options.DatabaseStatusResizing DatabaseStatusSuspended = options.DatabaseStatusSuspended DatabaseStatusSuspending = options.DatabaseStatusSuspending DatabaseStatusNonTerminated = options.DatabaseStatusNonTerminated DatabaseStatusAll = options.DatabaseStatusAll )
Re-export DatabaseStatus constants for convenience.
const DefaultAdminAPIVersion = "v2"
DefaultAdminAPIVersion is the default version of the Astra DevOps API.
Variables
var ErrCmdNilDb error = errors.New("command cannot execute with nil Db")
ErrCmdNilDb is returned when a command tries to execute with a nil db
var ErrEmptySlice error = errors.New("must be non-empty")
ErrEmptySlice is returned when an argument must be a non-empty slice.
var ErrNil error = errors.New("must be non-nil")
ErrNil is returned when an argument is nil.
var ErrNilFilter = errors.New("filter cannot be nil. If you want to delete all documents, use an empty filter instead")
var ErrNotFound error = errors.New("not found")
ErrNotFound is returned when a command returns "not found".
var ErrNotSlice error = errors.New("must be slice")
ErrNotSlice is returned when an argument should be a slice.
Functions
func EscapeFieldNames
func EscapeFieldNames(segments ...any) string
EscapeFieldNames escapes field names which may contain '.'s and '&'s for use in Data API queries. Accepts one or more path segments (string or int) and returns a dot-separated escaped field path.
Example:
EscapeFieldNames("websites", "www.datastax.com", "visits")
// Output: "websites.www&.datastax&.com.visits"
Important Usage Notes
This should NOT be used for insertion operations. It is only for use in areas where a field path is required; not just a field name (e.g. filters, projections, updates, etc.)
Segments should be of type string or int. Other types will be converted to strings
so you will be OK as long as you implement stringer.
Output:Example
package main
import (
"fmt"
"github.com/datastax/astra-db-go/v2/astra"
)
func main() {
fmt.Println(astra.EscapeFieldNames("websites", "www.datastax.com", "visits"))
fmt.Println(astra.EscapeFieldNames("shows", "tom&jerry", "episodes", 3, "views"))
}
websites.www&.datastax&.com.visits
shows.tom&&jerry.episodes.3.views
func NewDocumentTargetCtx
func NewDocumentTargetCtx() serdes.TargetDecodeCtx
func NewRowTargetCtx
func NewRowTargetCtx(cols table.Columns) serdes.TargetDecodeCtx
func UnescapeFieldPath
func UnescapeFieldPath(path string) ([]string, error)
UnescapeFieldPath splits a field path into its individual segments, accounting for escaped characters.
Returns an error if the path contains invalid escape sequences or malformed structure (e.g., leading/trailing dots, consecutive dots, or a trailing '&').
Types
type AstraAdmin
type AstraAdmin struct { // contains filtered or unexported fields }
AstraAdmin provides access to Astra DevOps API operations. Obtain an AstraAdmin instance from DataAPIClient.Admin(). Only valid for Astra environments.
func (*AstraAdmin) ClientOptions
func (a *AstraAdmin) ClientOptions() *options.APIOptions
ClientOptions returns the admin's options as a resolved struct with defaults.
func (*AstraAdmin) CreateDatabase
func (a *AstraAdmin) CreateDatabase(ctx context.Context, params CreateDatabaseParams, opts ...options.CreateDatabaseOption) (*AstraDatabaseAdmin, error)
CreateDatabase creates a new serverless vector database and returns an AstraDatabaseAdmin for performing admin operations on it.
The DevOps API endpoint is: POST https://api.astra.datastax.com/v2/databases
By default, this method blocks until the database reaches ACTIVE status (typically about 2 minutes). Use SetBlocking(false) to return immediately after the creation request is accepted.
Example - create a database (blocking by default):
admin, err := client.Admin()
dbAdmin, err := admin.CreateDatabase(ctx, astra.CreateDatabaseParams{
Name: "my-database",
CloudProvider: "gcp",
Region: "us-east1",
})
Example - create without waiting:
dbAdmin, err := admin.CreateDatabase(ctx, astra.CreateDatabaseParams{
Name: "my-database",
CloudProvider: "gcp",
Region: "us-east1",
}, options.CreateDatabase().SetBlocking(false))
Example - create with custom keyspace and poll interval:
dbAdmin, err := admin.CreateDatabase(ctx, astra.CreateDatabaseParams{
Name: "my-database",
CloudProvider: "aws",
Region: "us-east-1",
}, options.CreateDatabase().
SetKeyspace("my_keyspace").
SetPollInterval(5 * time.Second))
func (*AstraAdmin) DatabaseAdmin
func (a *AstraAdmin) DatabaseAdmin(id, region string, opts ...options.APIOption) *AstraDatabaseAdmin
DatabaseAdmin returns an AstraDatabaseAdmin handle for the given database ID and region.
No API calls are made; this simply creates a handle for performing admin operations on the specified database. Options provided override the defaults set on the DataAPIClient for the underlying Db instance.
Example:
dbAdmin := admin.DatabaseAdmin("a6a1d8d6-...-377566f345bf", "us-east1")
keyspaces, err := dbAdmin.ListKeyspaces(ctx)
func (*AstraAdmin) DatabaseAdminFromEndpoint
func (a *AstraAdmin) DatabaseAdminFromEndpoint(endpoint string, opts ...options.APIOption) *AstraDatabaseAdmin
DatabaseAdminFromEndpoint returns an AstraDatabaseAdmin handle for the given database endpoint.
The endpoint should be in the form https://<db_id>-<region>.apps.astra.datastax.com. No API calls are made; this simply creates a handle for performing admin operations on the specified database. Options provided override the defaults set on the DataAPIClient for the underlying Db instance.
Example:
dbAdmin := admin.DatabaseAdminFromEndpoint("https://<db_id>-<region>.apps.astra.datastax.com")
keyspaces, err := dbAdmin.ListKeyspaces(ctx)
func (*AstraAdmin) DatabaseInfo
func (a *AstraAdmin) DatabaseInfo(ctx context.Context, databaseID string, opts ...options.DatabaseInfoOption) (*FullAstraDatabaseInfo, error)
DatabaseInfo retrieves information about a specific database.
Example:
admin, err := client.Admin()
db, err := admin.DatabaseInfo(ctx, "database-id")
if err != nil {
log.Fatal(err)
}
fmt.Println("Status:", db.Status)
func (*AstraAdmin) DropDatabase
func (a *AstraAdmin) DropDatabase(ctx context.Context, databaseID string, opts ...options.DropDatabaseOption) error
DropDatabase terminates a database, permanently deleting all of its data.
The DevOps API endpoint is: POST https://api.astra.datastax.com/v2/databases/{id}/terminate
By default, this method blocks until the database is fully terminated (typically about 6-7 minutes). Use SetBlocking(false) to return immediately after the termination request is accepted.
WARNING: This action cannot be undone. All data, including automatic backups, will be permanently deleted.
Example - drop database (blocking by default):
admin, err := client.Admin() err = admin.DropDatabase(ctx, "database-id")
Example - drop without waiting:
err := admin.DropDatabase(ctx, "database-id",
options.DropDatabase().SetBlocking(false))
func (*AstraAdmin) FindAvailableRegions
func (a *AstraAdmin) FindAvailableRegions(ctx context.Context, opts ...options.FindAvailableRegionsOption) ([]Region, error)
FindAvailableRegions retrieves available serverless regions from the DevOps API.
Example - get all regions:
admin, err := client.Admin() regions, err := admin.FindAvailableRegions(ctx)
Example - filter by organization access:
regions, err := admin.FindAvailableRegions(ctx,
options.FindAvailableRegions().SetFilterByOrg(true))
func (*AstraAdmin) ListDatabases
func (a *AstraAdmin) ListDatabases(ctx context.Context, opts ...options.ListDatabasesOption) ([]FullAstraDatabaseInfo, error)
ListDatabases retrieves databases accessible to the caller.
By default, only non-terminated databases are returned (up to 25). Use SetLimit (up to 100) and SetStartingAfter to control pagination.
Example - list databases:
admin, err := client.Admin() databases, err := admin.ListDatabases(ctx)
Example - list only active GCP databases:
databases, err := admin.ListDatabases(ctx,
options.ListDatabases().
SetInclude(options.DatabaseStatusActive).
SetProvider(options.CloudProviderGCP))
Example - paginate through results and retrieve all databases:
func listAll(ctx context.Context, admin *astra.AstraAdmin) ([]astra.DatabaseInfo, error) {
var all []astra.DatabaseInfo
pageSize := 100
opts := options.ListDatabases().SetInclude(options.DatabaseStatusAll).SetLimit(pageSize)
for {
databases, err := admin.ListDatabases(ctx, opts)
if err != nil {
return nil, fmt.Errorf("admin.ListDatabases failed: %w", err)
}
all = append(all, databases...)
if len(databases) < pageSize {
break
}
// Set up cursor for next page
opts.SetStartingAfter(databases[len(databases)-1].ID)
}
return all, nil
}
type AstraDatabaseAdmin
type AstraDatabaseAdmin struct { // contains filtered or unexported fields }
AstraDatabaseAdmin provides admin operations for a specific Astra database via the DevOps API. Obtain an AstraDatabaseAdmin from AstraAdmin.CreateDatabase or AstraAdmin.DatabaseAdmin.
Example:
admin, err := client.Admin()
if err != nil {
log.Fatal(err)
}
dbAdmin, err := admin.CreateDatabase(ctx, astra.CreateDatabaseParams{
Name: "my-database",
CloudProvider: "gcp",
Region: "us-east1",
})
if err != nil {
log.Fatal(err)
}
keyspaces, err := dbAdmin.ListKeyspaces(ctx)
func (*AstraDatabaseAdmin) CreateKeyspace
func (a *AstraDatabaseAdmin) CreateKeyspace(ctx context.Context, keyspace string, opts ...options.CreateKeyspaceOption) error
CreateKeyspace creates a new keyspace in this database.
By default, this method blocks until the keyspace is visible. Use SetBlocking(false) to return immediately after the request is accepted.
Example:
err := dbAdmin.CreateKeyspace(ctx, "my_keyspace")
func (*AstraDatabaseAdmin) Db
func (a *AstraDatabaseAdmin) Db() *Db
Db returns the underlying Db handle.
func (*AstraDatabaseAdmin) Drop
func (a *AstraDatabaseAdmin) Drop(ctx context.Context, opts ...options.DropDatabaseOption) error
Drop terminates the database, permanently deleting all of its data.
By default, this method blocks until the database is fully terminated. Use SetBlocking(false) to return immediately after the termination request is accepted.
WARNING: This action cannot be undone.
Example:
err := dbAdmin.Drop(ctx)
func (*AstraDatabaseAdmin) DropKeyspace
func (a *AstraDatabaseAdmin) DropKeyspace(ctx context.Context, keyspace string, opts ...options.DropKeyspaceOption) error
DropKeyspace drops a keyspace from this database.
Example:
err := dbAdmin.DropKeyspace(ctx, "my_keyspace")
func (*AstraDatabaseAdmin) FindEmbeddingProviders
func (a *AstraDatabaseAdmin) FindEmbeddingProviders(ctx context.Context, opts ...options.FindEmbeddingProvidersOption) (*results.FindEmbeddingProvidersResult, error)
FindEmbeddingProviders returns information about all available embedding providers and their supported models, authentication methods, and parameters.
By default only SUPPORTED models are included. Use options.FindEmbeddingProvidersOptions to filter by a different lifecycle status, or pass options.ModelLifecycleStatusAll to include models of every status.
Example:
result, err := dbAdmin.FindEmbeddingProviders(ctx)
if err != nil {
return err
}
for name, provider := range result.EmbeddingProviders {
fmt.Printf("Provider: %s (%s)\n", name, provider.DisplayName)
for _, model := range provider.Models {
fmt.Printf(" Model: %s\n", model.Name)
}
}
Note: Warnings are accessible via the WarningHandler option callback only.
func (*AstraDatabaseAdmin) ID
func (a *AstraDatabaseAdmin) ID() string
ID returns the database ID.
func (*AstraDatabaseAdmin) Info
func (a *AstraDatabaseAdmin) Info(ctx context.Context, opts ...options.DatabaseInfoOption) (*FullAstraDatabaseInfo, error)
Info retrieves full database information from the DevOps API.
Example:
info, err := dbAdmin.Info(ctx)
fmt.Println("Status:", info.Status)
func (*AstraDatabaseAdmin) ListKeyspaces
func (a *AstraDatabaseAdmin) ListKeyspaces(ctx context.Context, opts ...options.ListKeyspacesOption) ([]string, error)
ListKeyspaces returns the keyspace names for this database, with the default keyspace first.
Example:
keyspaces, err := dbAdmin.ListKeyspaces(ctx)
type AstraDatabaseRegionInfo
type AstraDatabaseRegionInfo struct { // Name is the name of the region where the database is hosted, e.g. "us-east1". Name string `json:"name"` // APIEndpoint is the API endpoint for the region, e.g. "https://<db-id>-<region>.apps.astra.datastax.com". APIEndpoint string `json:"apiEndpoint"` // CreatedAt is the timestamp representing when this region was created. CreatedAt time.Time `json:"createdAt"` }
AstraDatabaseRegionInfo represents information about a region in which an Astra database is hosted.
This includes the region name, the API endpoint to use when interacting with that region, and the created-at timestamp.
Used within the regions field of FullAstraDatabaseInfo or similar types, which may include multiple region entries for multi-region databases.
type AwaitStatusOptions
type AwaitStatusOptions struct { // Will default to sane value PollInterval time.Duration // The status we are waiting for Target DatabaseStatus // Legal statuses that DB can/will enter before entering target status. LegalStates []DatabaseStatus // APIOptions are the API options to use for status checks. APIOptions *options.APIOptions }
func (*AwaitStatusOptions) Interval
func (o *AwaitStatusOptions) Interval() time.Duration
Interval returns PollInterval if non-zero and falls back to default.
func (*AwaitStatusOptions) IsStatusLegal
func (o *AwaitStatusOptions) IsStatusLegal(s DatabaseStatus) bool
IsStatusLegal returns true if the given status is in the list of legal states.
type BaseAstraDatabaseInfo
type BaseAstraDatabaseInfo struct { // ID is the unique database identifier. ID string // Name is the database name. Name string // Status is the current database status. Status DatabaseStatus // Keyspaces is the merged list of all keyspaces (default + additional). Keyspaces []string // CloudProvider is the cloud provider (e.g., "aws", "gcp", "azure"). CloudProvider string // Environment is the Astra environment. Environment options.AstraEnvironment // Raw is the raw DevOps API response, provided as an escape hatch // for fields not in the curated view. Raw *rawDatabaseResponse }
BaseAstraDatabaseInfo contains the common properties shared by both PartialAstraDatabaseInfo and FullAstraDatabaseInfo.
type Collection
type Collection struct { // contains filtered or unexported fields }
Collection represents a collection in an Astra DB database.
Options set on the collection are inherited by all commands executed on it, unless overridden at the command level.
func (*Collection) ClientOptions
func (c *Collection) ClientOptions() *options.APIOptions
ClientOptions returns the collection's options as a resolved struct with defaults.
func (*Collection) CountDocuments
func (c *Collection) CountDocuments(ctx context.Context, f CollectionFilter, upperBound int, opts ...options.CollectionCountDocumentsOption) (int, error)
CountDocuments counts documents after applying filter f. Count operations are expensive: for this reason, the best practice is to provide a reasonable upperBound.
Options passed here override those set on the collection.
func (*Collection) Database
func (c *Collection) Database() *Db
Database returns the parent database.
func (*Collection) DeleteMany
func (c *Collection) DeleteMany(ctx context.Context, f CollectionFilter, opts ...options.CollectionDeleteManyOption) (*results.DeleteResult, error)
DeleteMany deletes all documents matching the filter.
The Data API may not delete all matching documents in a single round-trip. This method automatically paginates, re-issuing the command and accumulating counts until the server indicates no more data remains.
An empty or nil filter deletes all documents in the collection. In that case, the returned DeletedCount is -1.
Options passed here override those set on the collection.
func (*Collection) DeleteOne
func (c *Collection) DeleteOne(ctx context.Context, f CollectionFilter, opts ...options.CollectionDeleteOneOption) (*results.DeleteResult, error)
DeleteOne deletes a single document matching the filter.
When the filter matches multiple documents, use the Sort option to control which document is deleted.
Options passed here override those set on the collection.
func (*Collection) Drop
func (c *Collection) Drop(ctx context.Context, opts ...options.DropCollectionOption) error
Drop deletes the collection and all its documents. Use with caution.
func (*Collection) EstimatedDocumentCount
func (c *Collection) EstimatedDocumentCount(ctx context.Context, opts ...options.CollectionEstimatedDocumentCountOption) (int, error)
EstimatedDocumentCount returns a rough estimate of the number of documents in the collection, much faster than CountDocuments but less precise. While it doesn't accept a filter, it can handle any number of documents, whereas CountDocuments may return an error if the count exceeds the upper bound.
Options passed here override those set on the collection.
func (*Collection) Find
func (c *Collection) Find(f CollectionFilter, opts ...options.CollectionFindOption) *cursors.CollectionFindCursor
Find returns a cursor for iterating over documents matching the filter.
The cursor automatically handles pagination, fetching new pages as needed.
The filter parameter defines criteria for selecting rows. Pass an empty filter.F{} or nil to find all rows (not recommended for large collections).
Use options to specify sorting, projection, limits, and other behaviors.
Example using Next/Decode pattern:
cursor := coll.Find(filter.F{"active": true})
defer cursor.Close()
for cursor.Next(ctx) {
var doc MyDocument
if err := cursor.Decode(&doc); err != nil {
return err
}
// Process doc
}
if err := cursor.Err(); err != nil {
return err
}
Example getting all results at once:
cursor := coll.Find(filter.F{})
var docs []MyDocument
if err := cursor.DecodeAll(ctx, &docs); err != nil {
return err
}
Example with vector search:
cursor := coll.Find(filter.F{},
options.CollectionFind().
SetSort(map[string]any{"$vector": []float32{0.1, 0.2, 0.3}}).
SetIncludeSimilarity(true),
)
In the unlikely case of an option validation error while creating the cursor, the cursor will be returned in an unclearable errored state.
func (*Collection) FindAndRerank
func (c *Collection) FindAndRerank(f CollectionFilter, opts ...options.CollectionFindAndRerankOption) cursors.FindAndRerankCursor
FindAndRerank returns a cursor for iterating over documents returned by a collection findAndRerank operation.
The cursor automatically handles pagination, fetching new pages as needed.
Use options to specify sorting, projection, limits, and other behaviors.
Example using Next/Decode pattern:
cursor := coll.FindAndRerank(filter.F{"active": true})
defer cursor.Close()
for cursor.Next(ctx) {
var doc MyDocument
if err := cursor.Decode(&doc); err != nil {
return err
}
// Process doc
}
if err := cursor.Err(); err != nil {
return err
}
In the unlikely case of an option validation error while creating the cursor, the cursor will be returned in an unclearable errored state.
func (*Collection) FindOne
func (c *Collection) FindOne(ctx context.Context, f CollectionFilter, opts ...options.CollectionFindOneOption) *results.SingleResult
FindOne finds a single document matching the filter.
Options passed here override those set on the collection.
func (*Collection) FindOneAndDelete
func (c *Collection) FindOneAndDelete(ctx context.Context, f CollectionFilter, opts ...options.CollectionFindOneAndDeleteOption) *results.SingleResult
FindOneAndDelete finds a single document matching the filter, deletes it, and returns the deleted document.
Options passed here override those set on the collection.
func (*Collection) FindOneAndReplace
func (c *Collection) FindOneAndReplace(ctx context.Context, f CollectionFilter, replacement any, opts ...options.CollectionFindOneAndReplaceOption) *results.SingleResult
FindOneAndReplace finds a single document matching the filter, replaces it, and returns the document. By default, the document is returned as it was before the replacement. Use options.ReturnDocumentAfter to return the document after the replacement.
The replacement parameter should be a new document without an _id set.
Options passed here override those set on the collection.
func (*Collection) FindOneAndUpdate
func (c *Collection) FindOneAndUpdate(ctx context.Context, f CollectionFilter, u CollectionUpdate, opts ...options.CollectionFindOneAndUpdateOption) *results.SingleResult
FindOneAndUpdate finds a single document matching the filter, applies the update, and returns the document. By default, the document is returned as it was before the update. Use options.ReturnDocumentAfter to return the document after the update.
The update parameter should be an update.U expression, e.g. update.Coll().Set("name", "new").
Options passed here override those set on the collection.
func (*Collection) InsertMany
func (c *Collection) InsertMany(ctx context.Context, documents any, opts ...options.CollectionInsertManyOption) (*results.InsertManyResult, error)
InsertMany inserts documents into the collection. Param documents must be a non-empty slice.
Options passed here override those set on the collection.
func (*Collection) InsertOne
func (c *Collection) InsertOne(ctx context.Context, document any, opts ...options.CollectionInsertOneOption) (*results.InsertOneResult, error)
InsertOne inserts a single document into the collection.
Options passed here override those set on the collection.
func (*Collection) Name
func (c *Collection) Name() string
Name returns the collection name.
func (*Collection) Options
func (c *Collection) Options(ctx context.Context, opts ...options.CollectionOptionsOption) (*results.CollectionDescriptor, error)
Options retrieves the collection's descriptor including its definition. This method calls the database's ListCollections and returns the descriptor for this specific collection.
Options passed here override those set on the collection.
func (*Collection) ReplaceOne
func (c *Collection) ReplaceOne(ctx context.Context, f CollectionFilter, replacement any, opts ...options.CollectionReplaceOneOption) (*results.UpdateResult, error)
ReplaceOne replaces a single document matching the filter.
The replacement parameter should be a new document without an _id set.
Options passed here override those set on the collection.
func (*Collection) UpdateMany
func (c *Collection) UpdateMany(ctx context.Context, f CollectionFilter, u CollectionUpdate, opts ...options.CollectionUpdateManyOption) (*results.UpdateResult, error)
UpdateMany updates all documents matching the filter.
The update parameter should be an update.U expression, e.g. update.Coll().Set("name", "new").
The Data API may not update all matching documents in a single round-trip. This method automatically paginates, re-issuing the command and accumulating counts until the server indicates no more data remains.
Options passed here override those set on the collection.
func (*Collection) UpdateOne
func (c *Collection) UpdateOne(ctx context.Context, f CollectionFilter, u CollectionUpdate, opts ...options.CollectionUpdateOneOption) (*results.UpdateResult, error)
UpdateOne updates a single document matching the filter.
The update parameter should be an update.U expression, e.g. update.Coll().Set("name", "new").
Options passed here override those set on the collection.
type CollectionFilter
type CollectionFilter = filter.Filterable
CollectionFilter is implemented by filter.F and filter.Filter. See the filter package for more details.
Example composing Filters:
f := filter.Gt("num_pages", 300)
Example using filter.F:
f := filter.F{"num_pages": filter.F{"$gt": 300}}
type CollectionUpdate
type CollectionUpdate = update.CollectionUpdate
CollectionUpdate is implemented by update.CollectionUpdateBuilder and update.U. See the update package for more details.
type CreateDatabaseParams
type CreateDatabaseParams struct { // Name is the database name. Must start and end with a letter or number. // Can contain letters, numbers, and special characters: & + - _ ( ) < > . , @ // Cannot exceed 50 characters. Name string // CloudProvider is the cloud provider (e.g., "aws", "gcp", "azure"). CloudProvider string // Region is the cloud provider region for the database location. Region string }
CreateDatabaseParams contains the required parameters for creating a database.
type DataAPIClient
type DataAPIClient struct { // contains filtered or unexported fields }
DataAPIClient is a client for interacting with an Astra DB database. Construct a new client using NewClient.
Options set on the client are inherited by all databases, collections, tables, and commands created from it, unless overridden at a lower level.
func NewClient
func NewClient(opts ...options.APIOption) *DataAPIClient
NewClient returns a new DataAPIClient with the given options.
Example:
client := astra.NewClient(
options.API().SetToken("AstraCS:..."),
)
Example with non-Astra backend:
client := astra.NewClient(
options.API().SetToken("AstraCS:..."),
options.API().SetDataAPIBackend(options.DataAPIBackendHCD),
)
func (*DataAPIClient) Admin
func (c *DataAPIClient) Admin(opts ...options.APIOption) (*AstraAdmin, error)
Admin returns an AstraAdmin handle for DevOps API operations. Returns an error if the client's environment is not an Astra environment.
Options set on the client are inherited by the AstraAdmin.
Example:
admin, err := client.Admin()
if err != nil {
log.Fatal(err)
}
regions, err := admin.FindAvailableRegions(ctx)
func (*DataAPIClient) ClientOptions
func (c *DataAPIClient) ClientOptions() *options.APIOptions
ClientOptions returns the client's options as a resolved struct with defaults.
func (*DataAPIClient) Database
func (c *DataAPIClient) Database(endpoint string, opts ...options.APIOption) *Db
Database returns a handle for the given database endpoint.
Options set here override those set on the client.
Example:
db := client.Database("https://...",
options.API().SetKeyspace("my_keyspace"),
)
type DataAPIDatabaseAdmin
type DataAPIDatabaseAdmin struct { // contains filtered or unexported fields }
DataAPIDatabaseAdmin provides keyspace operations via the Data API. Used for non-Astra environments (HCD, DSE, Cassandra).
func (*DataAPIDatabaseAdmin) CreateKeyspace
func (a *DataAPIDatabaseAdmin) CreateKeyspace(ctx context.Context, keyspace string, opts ...options.CreateKeyspaceOption) error
CreateKeyspace creates a new keyspace via the Data API.
func (*DataAPIDatabaseAdmin) DropKeyspace
func (a *DataAPIDatabaseAdmin) DropKeyspace(ctx context.Context, keyspace string, opts ...options.DropKeyspaceOption) error
DropKeyspace drops a keyspace via the Data API.
func (*DataAPIDatabaseAdmin) FindEmbeddingProviders
func (a *DataAPIDatabaseAdmin) FindEmbeddingProviders(ctx context.Context, opts ...options.FindEmbeddingProvidersOption) (*results.FindEmbeddingProvidersResult, error)
FindEmbeddingProviders returns detailed information about the availability and usage of the vectorize embedding providers available on the current database (may vary based on cloud provider & region).
Example:
result, err := dbAdmin.FindEmbeddingProviders(ctx)
if err != nil {
return err
}
// ["text-embedding-3-small", "text-embedding-3-large", "text-embedding-ada-002"]
for _, model := range result.EmbeddingProviders["openai"].Models {
fmt.Println(model.Name)
}
Note: Warnings are accessible via the WarningHandler option callback only.
func (*DataAPIDatabaseAdmin) ListKeyspaces
func (a *DataAPIDatabaseAdmin) ListKeyspaces(ctx context.Context, opts ...options.ListKeyspacesOption) ([]string, error)
ListKeyspaces returns the keyspace names for this database via the Data API.
type DatabaseAdmin
type DatabaseAdmin interface { ListKeyspaces(ctx context.Context, opts ...options.ListKeyspacesOption) ([]string, error) CreateKeyspace(ctx context.Context, keyspace string, opts ...options.CreateKeyspaceOption) error DropKeyspace(ctx context.Context, keyspace string, opts ...options.DropKeyspaceOption) error FindEmbeddingProviders(ctx context.Context, opts ...options.FindEmbeddingProvidersOption) (*results.FindEmbeddingProvidersResult, error) }
DatabaseAdmin provides keyspace management operations for a database. The concrete implementation depends on the environment:
- Astra environments use AstraDatabaseAdmin (DevOps API)
- Non-Astra environments use DataAPIDatabaseAdmin (Data API)
type DatabaseStatus
type DatabaseStatus = options.DatabaseStatus
DatabaseStatus is a type alias for options.DatabaseStatus, representing the status of an Astra database.
type Db
type Db struct { // contains filtered or unexported fields }
Db represents a connection to a specific Astra DB database.
Options set on the database are inherited by all collections, tables, and commands created from it, unless overridden at a lower level.
func (*Db) AlterType
func (d *Db) AlterType(ctx context.Context, name string, op table.AlterTypeOperation, opts ...options.AlterTypeOption) error
AlterType alters an existing user-defined type (UDT) in the database.
Example usage:
err := db.AlterType(ctx, "address", table.AddTypeFields{
Fields: table.Columns{
{Name: "country", Column: table.Text()},
},
})
func (*Db) Client
func (d *Db) Client() *DataAPIClient
Client returns the parent DataAPIClient.
func (*Db) ClientOptions
func (d *Db) ClientOptions() *options.APIOptions
ClientOptions returns the database's options as a resolved struct with defaults.
func (*Db) Collection
func (d *Db) Collection(name string, opts ...options.GetCollectionOption) *Collection
Collection returns a handle for the named collection.
Options set here override those set on the database.
Example:
coll := db.Collection("my_collection",
options.API().SetRequestTimeout(60 * time.Second),
)
func (*Db) CreateCollection
func (d *Db) CreateCollection(ctx context.Context, name string, opts ...options.CreateCollectionOption) (*Collection, error)
CreateCollection creates a collection in the database.
Options can be passed using the builder pattern or as raw structs:
// No options (simple collection)
coll, err := db.CreateCollection(ctx, "my_collection")
// With vector options
coll, err := db.CreateCollection(ctx, "my_collection",
options.CreateCollection().SetVector(&options.VectorOptions{
Dimension: 1024,
Metric: "cosine",
})
)
// Passing in options as raw struct
opts := &options.CreateCollectionOptions{
DefaultId: &options.CollectionDefaultIdOptions{
Type: options.DefaultIdTypeUUIDv7,
},
}
coll, err := db.CreateCollection(ctx, "my_collection", opts)
Note: warnings are accessible via the WarningHandler option callback only.
func (*Db) CreateTable
func (d *Db) CreateTable(ctx context.Context, name string, definition table.Definition, opts ...options.CreateTableOption) (*Table, error)
CreateTable creates a new table in the database with the specified definition.
The definition includes column names, data types, and the primary key configuration. After creating a table, you should index columns that you want to sort or filter to optimize queries.
Example usage:
definition := table.Definition{
Columns: table.Columns{
{Name: "title", Column: table.Text()},
{Name: "number_of_pages", Column: table.Int()},
{Name: "rating", Column: table.Float()},
{Name: "is_checked_out", Column: table.Boolean()},
},
PrimaryKey: table.PrimaryKey{
PartitionBy: []string{"title"},
},
}
tbl, err := db.CreateTable(ctx, "my_table", definition)
func (*Db) CreateType
func (d *Db) CreateType(ctx context.Context, name string, definition table.UDTDefinition, opts ...options.CreateTypeOption) error
CreateType creates a new user-defined type (UDT) in the database.
Example usage:
definition := table.UDTDefinition{
Fields: table.Columns{
{Name: "street", Column: table.Text()},
{Name: "city", Column: table.Text()},
{Name: "zip_code", Column: table.Int()},
},
}
err := db.CreateType(ctx, "address", definition)
func (*Db) DatabaseAdmin
func (d *Db) DatabaseAdmin() (DatabaseAdmin, error)
DatabaseAdmin returns a DatabaseAdmin for managing keyspaces on this database. The concrete implementation depends on the environment:
- Astra environments return an AstraDatabaseAdmin (DevOps API)
- Non-Astra environments return a DataAPIDatabaseAdmin (Data API)
func (*Db) DropCollection
func (d *Db) DropCollection(ctx context.Context, name string, opts ...options.DropCollectionOption) error
DropCollection drops a collection from the database. Note: warnings are accessible via the WarningHandler option callback only.
func (*Db) DropTable
func (d *Db) DropTable(ctx context.Context, name string, opts ...options.DropTableOption) error
DropTable drops (deletes) a table from the database.
Example usage:
err := db.DropTable(ctx, "my_table")
Note: warnings are accessible via the WarningHandler option callback only.
func (*Db) DropTableIndex
func (d *Db) DropTableIndex(ctx context.Context, name string, opts ...options.DropTableIndexOption) error
DropTableIndex drops (deletes) an index from the database.
Example usage:
err := db.DropTableIndex(ctx, "rating_idx")
Note: warnings are accessible via the WarningHandler option callback only.
func (*Db) DropType
func (d *Db) DropType(ctx context.Context, name string, opts ...options.DropTypeOption) error
DropType drops (deletes) a user-defined type (UDT) from the database.
Example usage:
err := db.DropType(ctx, "address")
func (*Db) Endpoint
func (d *Db) Endpoint() string
Endpoint returns the database API endpoint.
func (*Db) ID
func (d *Db) ID() (string, error)
ID returns the database UUID.
Only available for Astra databases connected via a standard endpoint (not a private endpoint).
Example:
db := client.Database("https://<db_id>-<region>.apps.astra.datastax.com")
id, err := db.ID() // "<db_id>"
Returns an error if the database is not an Astra database, or if the ID cannot be parsed from the endpoint URL.
func (*Db) Info
func (d *Db) Info(ctx context.Context, opts ...options.DatabaseInfoOption) (*PartialAstraDatabaseInfo, error)
Info retrieves partial database metadata based on the database's endpoint. This operation requires a call to the DevOps API, which is only available on Astra databases.
func (*Db) ListCollectionNames
func (d *Db) ListCollectionNames(ctx context.Context, opts ...options.ListCollectionsOption) ([]string, error)
ListCollectionNames lists the names of all collections in the database.
You can specify a keyspace in the options parameter, which will override the working keyspace for this Db instance.
Example:
names, err := db.ListCollectionNames(ctx)
if err != nil {
return err
}
for _, name := range names {
fmt.Printf("Collection: %s\n", name)
}
Options passed here override those set on the database.
func (*Db) ListCollections
func (d *Db) ListCollections(ctx context.Context, opts ...options.ListCollectionsOption) ([]results.CollectionDescriptor, error)
ListCollections lists all collections in the database with their full definitions.
You can specify a keyspace in the options parameter, which will override the working keyspace for this Db instance.
Example:
collections, err := db.ListCollections(ctx)
if err != nil {
return err
}
for _, coll := range collections {
fmt.Printf("Collection: %s\n", coll.Name)
if coll.Definition.Vector != nil {
fmt.Printf(" Vector dimension: %d\n", *coll.Definition.Vector.Dimension)
}
}
Options passed here override those set on the database.
func (*Db) ListTableNames
func (d *Db) ListTableNames(ctx context.Context, opts ...options.ListTablesOption) ([]string, error)
ListTableNames lists the names of all tables in the database.
Example:
names, err := db.ListTableNames(ctx)
if err != nil {
return err
}
for _, name := range names {
fmt.Printf("Table: %s\n", name)
}
Options passed here override those set on the database.
func (*Db) ListTables
func (d *Db) ListTables(ctx context.Context, opts ...options.ListTablesOption) ([]results.TableDescriptor, error)
ListTables lists all tables in the database with their full definitions.
You can specify API options via the options parameter to override settings for this command.
Example:
tables, err := db.ListTables(ctx)
if err != nil {
return err
}
for _, t := range tables {
fmt.Printf("Table: %s (%d columns)\n", t.Name, len(t.Definition.Columns))
}
Options passed here override those set on the database.
func (*Db) ListTypeNames
func (d *Db) ListTypeNames(ctx context.Context, opts ...options.ListTypesOption) ([]string, error)
ListTypeNames lists the names of all user-defined types (UDTs) in the database.
Example:
names, err := db.ListTypeNames(ctx)
if err != nil {
return err
}
for _, name := range names {
fmt.Printf("UDT: %s\n", name)
}
func (*Db) ListTypes
func (d *Db) ListTypes(ctx context.Context, opts ...options.ListTypesOption) ([]results.UDTDescriptor, error)
ListTypes lists all user-defined types (UDTs) in the database with their full definitions.
Example:
udts, err := db.ListTypes(ctx)
if err != nil {
return err
}
for _, u := range udts {
fmt.Printf("UDT: %s (%d fields)\n", u.Name, len(u.Definition.Fields))
}
func (*Db) Region
func (d *Db) Region() (string, error)
Region returns the database region (e.g. "us-east-1").
Only available for Astra databases connected via a standard endpoint (not a private endpoint).
Example:
db := client.Database("https://<db_id>-<region>.apps.astra.datastax.com")
region, err := db.Region() // "<region>"
Returns an error if the database is not an Astra database, or if the region cannot be parsed from the endpoint URL.
func (*Db) Table
func (d *Db) Table(name string, opts ...options.GetTableOption) *Table
Table returns a Table object for the specified table name. This does not create the table or verify its existence.
Options set here override those set on the database.
Example:
tbl := db.Table("my_table",
options.API().SetRequestTimeout(60 * time.Second),
)
func (*Db) UseKeyspace
func (d *Db) UseKeyspace(keyspace string)
UseKeyspace permanently switches the keyspace for this Db instance.
All future operations on this database, and any collections/tables created from it, will use the new keyspace by default.
Example:
db.UseKeyspace("new_keyspace")
type Document
type Document = untyped.Document
Document represents an untyped document used for a collection operation (as opposed to using a specific struct).
type FullAstraDatabaseInfo
type FullAstraDatabaseInfo struct { BaseAstraDatabaseInfo // Regions contains information about the regions where the database is deployed. // It will have at least one value, and may have more for multi-region deployments. Regions []AstraDatabaseRegionInfo // CreatedAt is when the database was created. CreatedAt time.Time // LastUsed is when the database was last used (zero if unknown). LastUsed time.Time // OrgID is the organization identifier. OrgID string // OwnerID is the owner's identifier. OwnerID string }
FullAstraDatabaseInfo is the complete metadata returned for an Astra database, flattening and simplifying the raw DevOps API response.
type NewDocument
type NewDocument = untyped.NewDocument
NewDocument is a map-based implementation of Document, primarily used for insertion.
type NewRow
type NewRow = untyped.NewRow
NewRow is a map-based implementation of Row, primarily used for insertion.
type PartialAstraDatabaseInfo
type PartialAstraDatabaseInfo struct { BaseAstraDatabaseInfo // Region is the region being used by the [Db] instance. Region string // APIEndpoint is the API endpoint for the region. APIEndpoint string }
PartialAstraDatabaseInfo is the partial metadata of a database, as returned from Db.Info, flattening and simplifying the raw DevOps API response.
type Region
type Region struct { // Classification indicates the region's classification level (e.g., "standard"). Classification string `json:"classification"` // CloudProvider is the cloud provider (e.g., "aws", "gcp", "azure"). CloudProvider string `json:"cloudProvider"` // DisplayName is the human-readable name of the region. DisplayName string `json:"displayName"` // Enabled indicates whether the region is currently available. Enabled bool `json:"enabled"` // Name is the region identifier used in API calls. Name string `json:"name"` // RegionType indicates the type of region (e.g., "serverless", "vector"). RegionType string `json:"region_type"` // ReservedForQualifiedUsers indicates if region is restricted. ReservedForQualifiedUsers bool `json:"reservedForQualifiedUsers"` // Zone is the geographic zone (e.g., "na", "eu", "apac"). Zone string `json:"zone"` }
Region represents an available serverless region from the DevOps API.
type Row
type Row = untyped.Row
Row represents an untyped row used for a table operation (as opposed to using a specific struct).
type Table
type Table struct { // contains filtered or unexported fields }
Table represents a table in the Astra DB.
Options set on the table are inherited by all commands executed on it, unless overridden at the command level.
func (*Table) Alter
func (t *Table) Alter(ctx context.Context, op table.AlterOperation, opts ...options.AlterTableOption) error
Alter modifies the table's schema. The operation provided (AddColumns, DropColumns, AddVectorize, or DropVectorize) determines the action taken.
Note that the Data API does not allow column type changes (drop and re-add instead) and does not support renaming a table. Dropping a vectorize integration preserves any embeddings already stored in the column; only the auto-embedding integration is removed.
After adding columns, index any new columns you intend to filter or sort on.
Example — add columns:
err := tbl.Alter(ctx, table.AddColumns{
Columns: table.Columns{
"is_summer_reading": table.Boolean(),
"library_branch": table.Text(),
},
})
Example — drop columns:
err := tbl.Alter(ctx, table.DropColumns{
Columns: []string{"borrower"},
})
Example — add vectorize on a vector column:
err := tbl.Alter(ctx, table.AddVectorize{
Columns: map[string]table.VectorService{
"summary_vec": {
Provider: "openai",
ModelName: "text-embedding-3-small",
Authentication: map[string]string{
"providerKey": "OPENAI_API_KEY",
},
},
},
})
Example — drop vectorize:
err := tbl.Alter(ctx, table.DropVectorize{
Columns: []string{"summary_vec"},
})
Note: warnings are accessible via the WarningHandler option callback only.
func (*Table) ClientOptions
func (t *Table) ClientOptions() *options.APIOptions
ClientOptions returns the table's options as a resolved struct with defaults.
func (*Table) CreateIndex
func (t *Table) CreateIndex(ctx context.Context, name string, column any, opts ...options.CreateIndexOption) error
CreateIndex creates an index on a column in the table.
The column parameter can be:
- A string for regular column indexes: "column_name"
- A map for indexing map column keys or values: map[string]string{"map_col": "$keys"}
For text columns, you can configure index behavior using SetAscii, SetNormalize, and SetCaseSensitive on the option builder.
Example - basic column index:
err := tbl.CreateIndex(ctx, "rating_idx", "rating")
Example - text column with case-insensitive matching:
err := tbl.CreateIndex(ctx, "title_idx", "title",
options.CreateIndex().SetCaseSensitive(false))
Example - map column keys index:
err := tbl.CreateIndex(ctx, "tags_idx", map[string]string{"tags": "$keys"})
Example - with ifNotExists:
err := tbl.CreateIndex(ctx, "rating_idx", "rating",
options.CreateIndex().SetIfNotExists(true))
Example - combining multiple option sources:
err := tbl.CreateIndex(ctx, "title_idx", "title",
options.CreateIndex().SetAscii(true),
options.CreateIndex().SetIfNotExists(true))
func (*Table) CreateTextIndex
func (t *Table) CreateTextIndex(ctx context.Context, name string, column string, opts ...options.CreateTextIndexOption) error
CreateTextIndex creates a text index on a text column in the table.
Example - basic text index:
err := tbl.CreateTextIndex(ctx, "content_idx", "content")
Example - with analyzer:
err := tbl.CreateTextIndex(ctx, "content_idx", "content",
options.CreateTextIndex().SetAnalyzer("standard"))
Example - with ifNotExists:
err := tbl.CreateTextIndex(ctx, "content_idx", "content",
options.CreateTextIndex().SetIfNotExists(true))
func (*Table) CreateVectorIndex
func (t *Table) CreateVectorIndex(ctx context.Context, name string, column string, opts ...options.CreateVectorIndexOption) error
CreateVectorIndex creates a vector index on a vector column in the table.
Vector indexes enable efficient similarity search on vector columns. You can configure the similarity metric and source model for optimization.
Example - basic vector index:
err := tbl.CreateVectorIndex(ctx, "embedding_idx", "embedding")
Example - with metric and source model:
err := tbl.CreateVectorIndex(ctx, "embedding_idx", "embedding",
options.CreateVectorIndex().SetMetric(options.MetricDotProduct).SetSourceModel("ada002"))
Example - with ifNotExists:
err := tbl.CreateVectorIndex(ctx, "embedding_idx", "embedding",
options.CreateVectorIndex().SetIfNotExists(true))
func (*Table) Database
func (t *Table) Database() *Db
Database returns the parent database.
func (*Table) Definition
func (t *Table) Definition(ctx context.Context, opts ...options.TableDefinitionOption) (*results.TableDescriptor, error)
Definition retrieves the table's descriptor including its definition. This method calls the database's ListTables and returns the descriptor for this specific table.
Options passed here override those set on the table.
func (*Table) DeleteMany
func (t *Table) DeleteMany(ctx context.Context, f TableFilter, opts ...options.TableDeleteManyOption) error
DeleteMany deletes all rows in the table matching the filter.
The filter must reference only primary-key columns per the Data API rules for table deleteMany. An empty filter (filter.F{}) deletes every row in the table; a nil filter is rejected to avoid accidental total deletes.
The Data API always returns deletedCount = -1 for this command, so no count is surfaced to the caller; the method returns only an error.
Options passed here override those set on the table.
Example:
err := tbl.DeleteMany(ctx,
filter.F{"title": "Hidden Shadows of the Past", "author": "John Anthony"},
)
func (*Table) DeleteOne
func (t *Table) DeleteOne(ctx context.Context, f TableFilter, opts ...options.TableDeleteOneOption) error
DeleteOne deletes a single row matching the filter.
The filter must describe the complete primary key using equality on primary-key columns. If no row matches, DeleteOne is a no-op and returns nil.
Options passed here override those set on the table.
Example:
err := tbl.DeleteOne(ctx,
filter.F{"title": "Hidden Shadows of the Past", "author": "John Anthony"},
)
func (*Table) Drop
func (t *Table) Drop(ctx context.Context, opts ...options.DropTableOption) error
Drop deletes the table and all its rows. Use with caution.
func (*Table) Find
func (t *Table) Find(f TableFilter, opts ...options.TableFindOption) *cursors.TableFindCursor
Find returns a cursor for iterating over rows matching the filter criteria.
The cursor automatically handles pagination, fetching new pages as needed.
The filter parameter defines criteria for selecting rows. Pass an empty filter.F{} or nil to find all rows (not recommended for large tables).
Use options to specify sorting, projection, limits, and other behaviors.
Example using Next/Decode pattern:
cursor := tbl.Find(filter.Eq("is_checked_out", false))
defer cursor.Close()
for cursor.Next(ctx) {
var row MyRow
if err := cursor.Decode(&row); err != nil {
return err
}
// Process row
}
if err := cursor.Err(); err != nil {
return err
}
Example getting all results at once:
cursor := tbl.Find(filter.F{})
var rows []MyRow
if err := cursor.DecodeAll(ctx, &rows); err != nil {
return err
}
Example with vector search:
cursor := tbl.Find(filter.F{},
options.TableFind().
SetSort(sort.Vector([]float32{0.1, 0.2, 0.3})).
SetIncludeSimilarity(true),
)
In the unlikely case of an option validation error while creating the cursor, the cursor will be returned in an unclearable errored state.
func (*Table) FindOne
func (t *Table) FindOne(ctx context.Context, f TableFilter, opts ...options.TableFindOneOption) *results.SingleResult
FindOne finds a single row in a table matching the filter criteria.
Example usage:
result := table.FindOne(ctx, filter.Eq("id", "some-uuid"))
var row MyRow
err := result.Decode(&row)
func (*Table) InsertMany
func (t *Table) InsertMany(ctx context.Context, rows any, opts ...options.TableInsertManyOption) (*results.InsertManyResult, error)
InsertMany inserts multiple rows into the table.
The rows parameter must be a non-empty slice of structs or maps representing the row data. The primary key columns must be included in each row.
Returns the inserted primary key values in the response.
Example usage:
books := []Book{
{Title: "Book 1", Author: "Author 1", NumberOfPages: 100, Rating: 4.0},
{Title: "Book 2", Author: "Author 2", NumberOfPages: 200, Rating: 4.5},
}
resp, err := table.InsertMany(ctx, books)
func (*Table) InsertOne
func (t *Table) InsertOne(ctx context.Context, row any, opts ...options.TableInsertOneOption) (*results.InsertOneResult, error)
InsertOne inserts a single row into the table.
The row parameter should be a struct or map representing the row data. The primary key columns must be included in the row data.
Returns the inserted primary key value(s) in the response.
Example usage:
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
NumberOfPages int `json:"number_of_pages"`
Rating float32 `json:"rating"`
}
book := Book{
Title: "The Great Gatsby",
Author: "F. Scott Fitzgerald",
NumberOfPages: 180,
Rating: 4.5,
}
resp, err := table.InsertOne(ctx, book)
func (*Table) ListIndexNames
func (t *Table) ListIndexNames(ctx context.Context, opts ...options.ListIndexesOption) ([]string, error)
ListIndexNames lists the names of all indexes on the table.
Example:
names, err := tbl.ListIndexNames(ctx)
if err != nil {
return err
}
for _, name := range names {
fmt.Printf("Index: %s\n", name)
}
Options passed here override those set on the database.
func (*Table) ListIndexes
func (t *Table) ListIndexes(ctx context.Context, opts ...options.ListIndexesOption) ([]results.IndexDescriptor, error)
ListIndexes lists all indexes on the table with their full definitions.
Example:
indexes, err := tbl.ListIndexes(ctx)
if err != nil {
return err
}
for _, idx := range indexes {
fmt.Printf("Index: %s on column %s\n", idx.Name, idx.Definition.Column)
}
Options passed here override those set on the database.
func (*Table) Name
func (t *Table) Name() string
Name returns the table name.
func (*Table) UpdateOne
func (t *Table) UpdateOne(ctx context.Context, f TableFilter, u TableUpdate, opts ...options.TableUpdateOneOption) error
UpdateOne updates a single row matching the filter.
The filter must describe the complete primary key using equality on primary-key columns. The update parameter should be an update.U expression built via update.Table(), e.g. update.Table().Set("rating", 4.5).Unset("borrower").
If no row matches and the update sets at least one non-null value, a new row is created (implicit upsert). You cannot update primary key values.
Options passed here override those set on the table.
Example:
err := tbl.UpdateOne(ctx,
filter.F{"title": "Hidden Shadows of the Past", "author": "John Anthony"},
update.Table().Set("rating", 4.5).Unset("borrower"),
)
type TableFilter
type TableFilter = filter.Filterable
TableFilter is implemented by filter.F and filter.Filter. See the filter package for more details.
f := filter.F{"num_pages": filter.F{"$gt": 300}}
type TableUpdate
type TableUpdate = update.TableUpdate
TableUpdate is implemented by update.TableUpdateBuilder and update.U. See the update package for more details.
type WithSimilarity
type WithSimilarity struct { Similarity float64 `json:"$similarity"` }
WithSimilarity is a struct that can be embedded in query result structs to include a similarity score for each result.
Example usage:
type MyDocument struct {
ID string `json:"id"`
Name string `json:"name"`
}
var result struct {
MyDocument
astra.WithSimilarity
}
err := coll.FindOne(ctx, filter.F{},
options.CollectionFindOne().
SetSort(sort.Vectorize("<search query>")).
SetIncludeSimilarity(true),
).Decode(&result)
if err == nil {
fmt.Printf("Match: '%s' (similarity: %f)\n", result.Name, result.Similarity)
}
Directories
| cursors | |
| datatypes | Package datatypes defines the data types used in the Astra DB Go client library. |
| filter | Package filter defines filtering options for Astra DB queries. |
| options | Package options provides options, types, and utilities for Astra DB operations. |
| ptr | Package ptr provides helper functions for working with pointers. |
| results | |
| serdes | |
| sort | Package sort provides type-safe sort specifications for Astra DB queries. |
| table | Package table provides types and utilities for working with Astra DB tables. |
| update | Package update provides helpers for constructing update documents for collection and table updates. |