Skip to main content

Cluster Transaction - Overview

Open Cluster-Wide Session

To open cluster transaction session you have to set the TransactionMode to TransactionMode.ClusterWide.

using (var session = store.OpenSession(new SessionOptions
{
TransactionMode = TransactionMode.ClusterWide
}))

You can store, delete and edit document and the session will track them as usual.

Working with Compare Exchange

Get Compare Exchange

session.Advanced.ClusterTransaction.GetCompareExchangeValue<T>(key);
Parameters
keystringThe key to retrieve
Return Value
CompareExchangeValue<T>If the key doesn't exists it will return null
session.Advanced.ClusterTransaction.GetCompareExchangeValues<T>(keys);
Parameters
keysstring[]Array of keys to retrieve
Return Value
Dictionary<string, CompareExchangeValue<T>>If a key doesn't exists the associate value will be null

Create Compare Exchange

session.Advanced.ClusterTransaction.CreateCompareExchangeValue(key, value);
Parameters
keystringThe key to save with the associate value. This string can be up to 512 bytes.
valueTThe value to store

If the value is already exists SaveChanges() will throw a ConcurrencyException.

// occupy "Best NoSQL Transactional Database" to be "RavenDB"
session.Advanced.ClusterTransaction.CreateCompareExchangeValue(key: "Best NoSQL Transactional Database", value: "RavenDB");
session.SaveChanges();

Update Compare Exchange

session.Advanced.ClusterTransaction.UpdateCompareExchangeValue(new CompareExchangeValue<T>(key, index, value));
Parameters
itemCompareExchangeValue<T>The item to update

If the value was changed by someone else the SaveChanges() will throw a ConcurrencyException.

_async
// load the existing dns record of ravendb.net
CompareExchangeValue<DNS> result = await session.Advanced.ClusterTransaction.GetCompareExchangeValueAsync<DNS>(key: "ravendb.net");

// change the ip
result.Value.IpAddress = "52.32.173.150";
session.Advanced.ClusterTransaction.UpdateCompareExchangeValue(result);

// save the changes
await session.SaveChangesAsync();

Delete Compare Exchange

session.Advanced.ClusterTransaction.DeleteCompareExchangeValue(key, index);
Parameters
keystringThe key to save with the associate value
indexlongIndex for concurrency control

CompareExchangeValue

Parameters
keystringKey of the item to store. This string can be up to 512 bytes.
indexlongIndex for concurrency control
valueTThe actual value to keep