Create Database Operation



Create new database

Example I - Create non-sharded database

  • The following simple example creates a non-sharded database with the default replication factor of 1.

// Define the create database operation, pass an instance of DatabaseRecord
var createDatabaseOp = new CreateDatabaseOperation(new DatabaseRecord("DatabaseName"));

// Execute the operation by passing it to Maintenance.Server.Send
store.Maintenance.Server.Send(createDatabaseOp);
// Define the create database operation, pass an instance of DatabaseRecord
var createDatabaseOp = new CreateDatabaseOperation(new DatabaseRecord("DatabaseName"));

// Execute the operation by passing it to Maintenance.Server.SendAsync
await store.Maintenance.Server.SendAsync(createDatabaseOp);
// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(builder => builder
     // Call 'Regular' to create a non-sharded database
    .Regular("DatabaseName"));

// Execute the operation by passing it to Maintenance.Server.Send
store.Maintenance.Server.Send(createDatabaseOp);
// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(builder => builder
     // Call 'Regular' to create a non-sharded database
    .Regular("DatabaseName"));

// Execute the operation by passing it to Maintenance.Server.SendAsync
await store.Maintenance.Server.SendAsync(createDatabaseOp);

Example II - Create sharded database

  • The following example creates a sharded database with 3 shards, each with a replication factor of 2.
  • In addition, it enables:
    • revisions
    • document expiration
    • and applies some settings to the database.

// Define the database record:
var databaseRecord = new DatabaseRecord("ShardedDatabaseName") {
    
    // Configure sharding:
    Sharding = new ShardingConfiguration()
    {
        // Ensure nodes "A", "B", and "C" are available in the cluster
        // before executing the database creation.
        Shards = new Dictionary<int, DatabaseTopology>()
        {
            {0, new DatabaseTopology { Members = new List<string> { "A", "B" }}},
            {1, new DatabaseTopology { Members = new List<string> { "A", "C" }}},
            {2, new DatabaseTopology { Members = new List<string> { "B", "C" }}}
        }
    },
    
    // Enable revisions on all collections:
    Revisions = new RevisionsConfiguration()
    {
        Default = new RevisionsCollectionConfiguration()
        {
            Disabled = false, MinimumRevisionsToKeep = 5
        }
    },
    
    // Enable the document expiration feature:
    Expiration = new ExpirationConfiguration()
    {
        Disabled = false
    },
    
    // Apply some database configuration setting:
    Settings = new Dictionary<string, string>()
    {
        {"Databases.QueryTimeoutInSec", "500"}
    }
};

// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(databaseRecord);

// Execute the operation by passing it to Maintenance.Server.Send
store.Maintenance.Server.Send(createDatabaseOp);
// Define the database record:
var databaseRecord = new DatabaseRecord("ShardedDatabaseName") {
    
    // Configure sharding:
    Sharding = new ShardingConfiguration()
    {
        // Ensure nodes "A", "B", and "C" are available in the cluster
        // before executing the database creation.
        Shards = new Dictionary<int, DatabaseTopology>()
        {
            {0, new DatabaseTopology { Members = new List<string> { "A", "B" }}},
            {1, new DatabaseTopology { Members = new List<string> { "A", "C" }}},
            {2, new DatabaseTopology { Members = new List<string> { "B", "C" }}}
        }
    },
    
    // Enable revisions on all collections:
    Revisions = new RevisionsConfiguration()
    {
        Default = new RevisionsCollectionConfiguration()
        {
            Disabled = false, MinimumRevisionsToKeep = 5
        }
    },
    
    // Enable the document expiration feature:
    Expiration = new ExpirationConfiguration()
    {
        Disabled = false
    },
    
    // Apply some database configuration setting:
    Settings = new Dictionary<string, string>()
    {
        {"Databases.QueryTimeoutInSec", "500"}
    }
};

// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(databaseRecord);

// Execute the operation by passing it to Maintenance.Server.SendAsync
await store.Maintenance.Server.SendAsync(createDatabaseOp);
// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(builder => builder
        
    // Call 'Sharded' to create a sharded database
    .Sharded("ShardedDatabaseName", topology => topology
        // Ensure nodes "A", "B", and "C" are available in the cluster
        // before executing the database creation.
        .AddShard(0, new DatabaseTopology {Members = new List<string> {"A", "B"}})
        .AddShard(1, new DatabaseTopology {Members = new List<string> {"A", "C"}})
        .AddShard(2, new DatabaseTopology {Members = new List<string> {"B", "C"}}))
    // Enable revisions on all collections:
    .ConfigureRevisions(new RevisionsConfiguration()
    {
        Default = new RevisionsCollectionConfiguration()
        {
            Disabled = false, MinimumRevisionsToKeep = 5
        }
    })
    // Enable the document expiration feature:
    .ConfigureExpiration(new ExpirationConfiguration()
    {
        Disabled = false
    })
    // Apply some database configuration setting:
    .WithSettings(new Dictionary<string, string>()
    {
        { "Databases.QueryTimeoutInSec", "500" }
    })
);

// Execute the operation by passing it to Maintenance.Server.Send
store.Maintenance.Server.Send(createDatabaseOp);
// Define the create database operation
var createDatabaseOp = new CreateDatabaseOperation(builder => builder
        
    // Call 'Sharded' to create a sharded database
    .Sharded("ShardedDatabaseName", topology => topology
        // Ensure nodes "A", "B", and "C" are available in the cluster
        // before executing the database creation.
        .AddShard(0, new DatabaseTopology {Members = new List<string> {"A", "B"}})
        .AddShard(1, new DatabaseTopology {Members = new List<string> {"A", "C"}})
        .AddShard(2, new DatabaseTopology {Members = new List<string> {"B", "C"}}))
    // Enable revisions on all collections:
    .ConfigureRevisions(new RevisionsConfiguration()
    {
        Default = new RevisionsCollectionConfiguration()
        {
            Disabled = false, MinimumRevisionsToKeep = 5
        }
    })
    // Enable the document expiration feature:
    .ConfigureExpiration(new ExpirationConfiguration()
    {
        Disabled = false
    })
    // Apply some database configuration setting:
    .WithSettings(new Dictionary<string, string>()
    {
        { "Databases.QueryTimeoutInSec", "500" }
    })
);

// Execute the operation by passing it to Maintenance.Server.SendAsync
await store.Maintenance.Server.SendAsync(createDatabaseOp);

Example III - Ensure database does not exist before creating

  • To ensure the database does not already exist before creating it, follow this example:

var databaseName = "MyDatabaseName";

try
{
    // Try to fetch database statistics to check if the database exists
    store.Maintenance.ForDatabase(databaseName)
        .Send(new GetStatisticsOperation());
}
catch (DatabaseDoesNotExistException)
{
    try
    {
        // The database does not exist, try to create:
        var createDatabaseOp = new CreateDatabaseOperation(
            new DatabaseRecord(databaseName));
        
        store.Maintenance.Server.Send(createDatabaseOp);
    }
    catch (ConcurrencyException)
    {
        // The database was created by another client before this call completed
    }
}
var databaseName = "MyDatabaseName";

try
{
    // Try to fetch database statistics to check if the database exists:
    await store.Maintenance.ForDatabase(databaseName)
        .SendAsync(new GetStatisticsOperation());
}
catch (DatabaseDoesNotExistException)
{
    try
    {
        // The database does not exist, try to create:
        var createDatabaseOp = new CreateDatabaseOperation(
            new DatabaseRecord(databaseName));
        
        await store.Maintenance.Server.SendAsync(createDatabaseOp);
    }
    catch (ConcurrencyException)
    {
        // The database was created by another client before this call completed
    }
}

Syntax

// CreateDatabaseOperation overloads:
// ==================================
public CreateDatabaseOperation(DatabaseRecord databaseRecord) {}
public CreateDatabaseOperation(DatabaseRecord databaseRecord, int replicationFactor) {}
public CreateDatabaseOperation(Action<IDatabaseRecordBuilderInitializer> builder) {}
Parameter Description
databaseRecord Instance of DatabaseRecord containing database configuration.
See The Database Record below.
replicationFactor Number of nodes the database should be replicated to.

If not specified, the value is taken from databaseRecord.Topology.ReplicationFactor,
or defaults to 1 if that is not set.

If Topology is provided, the replicationFactor is ignored.
builder Callback used to initialize and fluently configure a new DatabaseRecord.
Receives an IDatabaseRecordBuilderInitializer on which you invoke builder methods to construct the record. See The Database Record Builder below.

The Database Record:

The DatabaseRecord is a collection of database configurations:

DatabaseRecord constructors Description
DatabaseRecord() Initialize a new database record.
DatabaseRecord(string databaseName) Initialize a new database record with the specified database name.

Note:

  • Only the properties listed in the table below can be configured in the DatabaseRecord object passed to CreateDatabaseOperation.
  • For example, although ongoing task definitions are public on the DatabaseRecord class, setting them during database creation will result in an exception. To define ongoing tasks (e.g., backups, ETL, replication), use the appropriate dedicated operation after the database has been created.

DatabaseRecord properties Type Description
AiConnectionStrings Dictionary<string, AiConnectionString> Define Ai Connection Strings, keyed by name.
Analyzers Dictionary<string, AnalyzerDefinition> A dictionary defining the Custom Analyzers available to the database.
AutoIndexes Dictionary<string, AutoIndexDefinition> Auto-index definitions for the database.
Client ClientConfiguration Client behavior configuration.
ConflictSolverConfig ConflictSolver Define the strategy used to resolve Replication conflicts.
DataArchival DataArchivalConfiguration Data Archival configuration for the database.
DatabaseName string The database name.
Disabled bool Set the database initial state.
true - disable the database.
false - (default) the database will be enabled.

This can be modified later via ToggleDatabasesStateOperation.
DocumentsCompression DocumentsCompressionConfiguration Configuration settings for Compressing documents.
ElasticSearchConnectionStrings Dictionary<string, ElasticSearchConnectionString> Define ElasticSearch Connection Strings, keyed by name.
Encrypted bool true - create an Encrypted database.

Note: Use PutSecretKeyCommand to send your secret key to the server BEFORE creating the database.

false - (default) the database will not be encrypted.
Expiration ExpirationConfiguration Expiration configuration for the database.
Indexes Dictionary<string, IndexDefinition> Define Indexes that will be created with the database - no separate deployment needed.
Integrations IntegrationConfigurations Configuration for Integrations,
e.g. PostgreSqlConfiguration.
LockMode DatabaseLockMode Set the database lock mode.
(default: Unlock)

This can be modified later via SetDatabasesLockOperation.
OlapConnectionStrings Dictionary<string, OlapConnectionString> Define OLAP Connection Strings, keyed by name.
QueueConnectionStrings Dictionary<string, QueueConnectionString> Define Queue Connection Strings, keyed by name.
RavenConnectionStrings Dictionary<string, RavenConnectionString> Define Raven Connection Strings, keyed by name.
Refresh RefreshConfiguration Refresh configuration for the database.
Revisions RevisionsConfiguration Revisions configuration for the database.
RevisionsBin RevisionsBinConfiguration Configuration for the Revisions Bin Cleaner.
RevisionsForConflicts RevisionsCollectionConfiguration Set the revisions configuration for conflicting documents.
RollingIndexes Dictionary<string, RollingIndex> Dictionary mapping index names to their deployment configurations.
Settings Dictionary<string, string> Configuration settings for the database.
Sharding ShardingConfiguration The sharding configuration.
SnowflakeConnectionStrings Dictionary<string, SnowflakeConnectionString> Define Snowflake Connection Strings, keyed by name.
Sorters Dictionary<string, SorterDefinition> A dictionary defining the Custom Sorters available to the database.
SqlConnectionStrings Dictionary<string, SqlConnectionString> Define SQL Connection Strings, keyed by name.
Studio StudioConfiguration Studio Configuration.
TimeSeries TimeSeriesConfiguration Time series configuration for the database.
Topology DatabaseTopology Optional topology configuration.

Defaults to null, in which case the server will determine which nodes to place the database on, based on the specified ReplicationFactor.
UnusedDatabaseIds HashSet<string> Set database IDs that will be excluded when creating new change vectors.

The Database Record Builder:

public interface IDatabaseRecordBuilderInitializer
{
    public IDatabaseRecordBuilder Regular(string databaseName);
    public IShardedDatabaseRecordBuilder Sharded(string databaseName, Action<IShardedTopologyConfigurationBuilder> builder);
    public DatabaseRecord ToDatabaseRecord();
}

public interface IShardedDatabaseRecordBuilder : IDatabaseRecordBuilderBase
{
}

// Available configurations:
// =========================

public interface IDatabaseRecordBuilder : IDatabaseRecordBuilderBase
{
    public IDatabaseRecordBuilderBase WithTopology(DatabaseTopology topology);
    public IDatabaseRecordBuilderBase WithTopology(Action<ITopologyConfigurationBuilder> builder);
    public IDatabaseRecordBuilderBase WithReplicationFactor(int replicationFactor);
}

public interface IDatabaseRecordBuilderBase
{
    DatabaseRecord ToDatabaseRecord();

    IDatabaseRecordBuilderBase ConfigureClient(ClientConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureDocumentsCompression(DocumentsCompressionConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureExpiration(ExpirationConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureRefresh(RefreshConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureRevisions(RevisionsConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureStudio(StudioConfiguration configuration);
    IDatabaseRecordBuilderBase ConfigureTimeSeries(TimeSeriesConfiguration configuration);

    IDatabaseRecordBuilderBase Disabled();
    IDatabaseRecordBuilderBase Encrypted();

    IDatabaseRecordBuilderBase WithAnalyzers(params AnalyzerDefinition[] analyzerDefinitions);
    IDatabaseRecordBuilderBase WithConnectionStrings(Action<IConnectionStringConfigurationBuilder> builder);
    IDatabaseRecordBuilderBase WithIndexes(params IndexDefinition[] indexDefinitions);
    IDatabaseRecordBuilderBase WithIntegrations(Action<IIntegrationConfigurationBuilder> builder);
    IDatabaseRecordBuilderBase WithLockMode(DatabaseLockMode lockMode);
    IDatabaseRecordBuilderBase WithSettings(Dictionary<string, string> settings);
    IDatabaseRecordBuilderBase WithSettings(Action<Dictionary<string, string>> builder);
    IDatabaseRecordBuilderBase WithSorters(params SorterDefinition[] sorterDefinitions);
}