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 same transaction, BatchCommand should be used.

Syntax

public BatchCommand(DocumentConventions conventions, JsonOperationContext context, List<ICommandData> commands, BatchOptions options = null)

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)
    };

    var batch = new BatchCommand(documentStore.Conventions, session.Advanced.Context, commands);
    session.Advanced.RequestExecutor.Execute(batch, session.Advanced.Context);
}
using (var session = documentStore.OpenAsyncSession())
{
    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)
    };

    var batch = new BatchCommand(documentStore.Conventions, session.Advanced.Context, commands);
    await session.Advanced.RequestExecutor.ExecuteAsync(batch, session.Advanced.Context);
}

Note

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.