import Admonition from '@theme/Admonition'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock';
-
Use
CreateDatabaseOperationto create a new database from the Client API, as described below.
To create a new database from the Studio, see Create database. -
This operation requires a client certificate with a security clearance of Operator or ClusterAdmin.
To learn which operations are allowed at each level, see Security clearance and permissions. -
In this article:
Sizing the database group
The default replication factor is 1, which puts the database on a single node. For high availability, set the replication factor to at least 3 so the database survives losing a node and stays synchronized through internal replication.
If the database also uses
cluster-wide transactions,
prefer an odd replication factor (3, 5, or 7).
A cluster-wide transaction commits only after a majority of the database
group's voting members have accepted it, and an odd group size means that majority
is always a clean (n/2 + 1) - never a tie.
For the full reasoning, see Cluster: Best Practices.
- The following simple example creates a non-sharded database with the default replication factor of 1.
// Execute the operation by passing it to Maintenance.Server.Send
store.Maintenance.Server.Send(createDatabaseOp);
} </CodeBlock> </TabItem> <TabItem value="Create_db_async" label="Create_db_async"> <CodeBlock language="csharp"> {// 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);
} </CodeBlock> </TabItem> <TabItem value="Create_using_builder_sync" label="Create_using_builder_sync"> <CodeBlock language="csharp"> {// 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);
} </CodeBlock> </TabItem> <TabItem value="Create_using_builder_async" label="Create_using_builder_async"> <CodeBlock language="csharp"> {// 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); `}
- 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.
// 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);
} </CodeBlock> </TabItem> <TabItem value="Create_db_async" label="Create_db_async"> <CodeBlock language="csharp"> {// 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);
} </CodeBlock> </TabItem> <TabItem value="Create_using_builder_sync" label="Create_using_builder_sync"> <CodeBlock language="csharp"> {// 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);
} </CodeBlock> </TabItem> <TabItem value="Create_using_builder_async" label="Create_using_builder_async"> <CodeBlock language="csharp"> {// 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); `}
- To ensure the database does not already exist before creating it, follow this example:
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
}
}
} </CodeBlock> </TabItem> <TabItem value="Async" label="Async"> <CodeBlock language="csharp"> {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
}
} `}
{`// CreateDatabaseOperation overloads: // ================================== public CreateDatabaseOperation(DatabaseRecord databaseRecord) \{\} public CreateDatabaseOperation(DatabaseRecord databaseRecord, int replicationFactor) \{\} public CreateDatabaseOperation(Action 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 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
DatabaseRecordobject passed toCreateDatabaseOperation. - 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 |
|---|---|---|
| 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. |
| 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. |
public interface IShardedDatabaseRecordBuilder : IDatabaseRecordBuilderBase { }
// Available configurations: // =========================
public interface IDatabaseRecordBuilder : IDatabaseRecordBuilderBase { public IDatabaseRecordBuilderBase WithTopology(DatabaseTopology topology); public IDatabaseRecordBuilderBase WithTopology(Action 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);
} `}