Skip to main content

Batches: How to Send Multiple Commands Using a Batch

To send multiple commands in a single request, reducing the number of remote calls and allowing several operations to share the same transaction, SingleNodeBatchCommand should be used.

In this page:

Syntax

public SingleNodeBatchCommand(DocumentConventions conventions, JsonOperationContext context, 
List<ICommandData> commands, BatchOptions options = null,
TransactionMode mode = TransactionMode.SingleNode)

The following commands can be sent using a batch

  • DeleteAttachmentCommandData
  • DeleteCommandData
  • DeletePrefixedCommandData
  • PatchCommandData
  • PutAttachmentCommandData
  • PutCommandData

Batch Options

public class BatchOptions
{
public bool WaitForReplicas { get; set; }
//if set to true, will wait for replication to be performed on at least a majority
//of DB instances (applies only when WaitForReplicas is set to true)

public bool Majority { get; set; }

public int NumberOfReplicasToWaitFor { get; set; }

public TimeSpan WaitForReplicasTimeout { get; set; }

public bool ThrowOnTimeoutInWaitForReplicas { get; set; }

public bool WaitForIndexes { get; set; }

public TimeSpan WaitForIndexesTimeout { get; set; }

public bool ThrowOnTimeoutInWaitForIndexes { get; set; }

public string[] WaitForSpecificIndexes { get; set; }

public TimeSpan? RequestTimeout { get; set; }
}

Example

using (var session = documentStore.OpenSession())
{
var commands = new List<ICommandData>
{
new PutCommandData("users/3", null, new DynamicJsonValue
{
["Name"] = "James"
}),
new PatchCommandData("users/1-A", null, new PatchRequest
{
Script = "this.Name = 'Nhoj';"
}, null),
new DeleteCommandData("users/2-A", null)
};

// By including the method SingleNodeBatchCommand(),
// multiple commands can be executed in a single request
// and several operations can share the same transaction.
var batch = new SingleNodeBatchCommand(documentStore.Conventions, session.Advanced.Context, commands);
session.Advanced.RequestExecutor.Execute(batch, session.Advanced.Context);
}

All the commands in the batch will succeed or fail as a transaction. Other users will not be able to see any of the changes until the entire batch completes.