Data subscriptions: Revisions support
-
When the Revisions feature is enabled, a revision is created with each change made in a document.
Each revision is a snapshot of the document at the time of the change. Over time, a complete audit trail is formed. -
A data subscription can subscribe not only to documents but also to their revisions, allowing workers to track the changes made in documents over time.
-
To subscribe to revisions, use Revision<T> as the subscription's item type, or add
(Revisions = true)to its RQL query. -
In this article:
Regular subscription vs revisions subscription
A subscription can target a collection's documents or their revisions. The two behave differently in what they process, what the server-side query can see, and what reaches the worker.
Regular subscription
- Processed items
The subscription selects documents from the defined collection. Only the current version of each document is selected, even if the document has revisions. - Query access scope
The subscription query running on the server has access only to the current version of each document. - Data sent to the worker
Each item in the batch contains a single document, or a projection of it, as defined in the subscription.
Revisions subscription
- Processed items
The subscription selects all revisions of documents from the defined collection, including revisions of deleted documents from the revisions bin if they have not been purged. - Query access scope
For each revision, the subscription query running on the server has access to both the revision being processed and its preceding revision, so it can compare the two revisions and act on what changed between them. - Data sent to the worker
Unless the query projects specific fields, each item in the batch contains both the processed revision (Result.Current) and its preceding revision (Result.Previous).
One of the two fields isnullin these cases:- For a document's first revision,
Result.Previousisnull. - For the revision created when the document is deleted,
Result.Currentisnull.
- For a document's first revision,
-
For a revisions subscription to work, Revisions must be configured and enabled for the collection the subscription targets.
-
A document that has no revisions is not processed, so make sure your revisions configuration does not purge revisions before the subscription has had a chance to process them.
-
A revisions subscription ignores the processing behavior for archived documents and selects the revisions of archived and non-archived documents alike.
Revisions processing order
In a revisions subscription, the worker receives revisions in consecutive pairs: each revision
together with the one immediately before it.
This gives the worker, and the subscription query, the document's state both before and after every
change, so they can detect what changed and act on it, for example to filter or project by the difference.
For example, take this User document:
{
"Name": "James",
"Age": "21"
}
Suppose its Age field is then updated twice, first to 22 and then to 23. The worker receives
three batch items, each pairing a revision with the one before it:
| Batch item | Previous | Current |
|---|---|---|
| item #1 | null | { Name: "James", Age: "21" } |
| item #2 | { Name: "James", Age: "21" } | { Name: "James", Age: "22" } |
| item #3 | { Name: "James", Age: "22" } | { Name: "James", Age: "23" } |
The first item pairs the document's creation with a null previous. Each later item carries the
earlier revision as Previous and the next as Current.
Creating and consuming a revisions subscription
This basic revisions subscription delivers to the worker pairs of consecutive Order revisions.
Example: Creating the subscription
- Generic API
- RQL
subscriptionName = store.Subscriptions.Create(
// Use Revision<T> as the processed-item type, e.g. Revision<Order>
new SubscriptionCreationOptions<Revision<Order>>());
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
// Add (Revisions = true) to the subscription's RQL
Query = @"from Orders (Revisions = true)"
});
Example: Consuming the subscription
SubscriptionWorker<Revision<Order>> revisionsWorker =
store.Subscriptions.GetSubscriptionWorker<Revision<Order>>(subscriptionName);
await revisionsWorker.Run((SubscriptionBatch<Revision<Order>> batch) =>
{
foreach (var item in batch.Items)
{
// The preceding revision (null for a document's first revision)
var previousRevision = item.Result.Previous;
// The revision being processed
var currentRevision = item.Result.Current;
ProcessOrderRevisions(previousRevision, currentRevision); // your processing logic
}
});
Filtering revisions
This subscription sends to the worker only the revisions in which the order was shipped to Mexico.
Example: Creating the subscription
- Generic API
- RQL
subscriptionName = store.Subscriptions.Create(
new SubscriptionCreationOptions<Revision<Order>>()
{
// Only revisions of orders shipped to Mexico are sent to the worker
Filter = revision => revision.Current.ShipTo.Country == "Mexico"
});
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
Query = @"declare function isSentToMexico(doc) {
return doc.Current.ShipTo.Country == 'Mexico'
}
from 'Orders' (Revisions = true) as doc
where isSentToMexico(doc) == true"
});
Example: Consuming the subscription
SubscriptionWorker<Revision<Order>> worker =
store.Subscriptions.GetSubscriptionWorker<Revision<Order>>(subscriptionName);
await worker.Run(batch =>
{
foreach (var item in batch.Items)
{
Console.WriteLine($@"
This is a revision of document {item.Id}.
The order in this revision was shipped at {item.Result.Current.ShippedAt}.");
}
});
Projecting fields from revisions
This subscription filters the revisions and sends to the worker only the projected data rather than the full revision pair.
Example: Creating the subscription
- Generic API
- RQL
subscriptionName = store.Subscriptions.Create(
new SubscriptionCreationOptions<Revision<Order>>()
{
// Process only revisions whose revenue exceeds the preceding revision's by more than 2500
Filter = revision =>
revision.Previous != null &&
revision.Current.Lines.Sum(x => x.PricePerUnit * x.Quantity) >
revision.Previous.Lines.Sum(x => x.PricePerUnit * x.Quantity) + 2500,
// Project the fields sent to the worker
Projection = revision => new OrderRevenues()
{
PreviousRevenue = revision.Previous.Lines.Sum(x => x.PricePerUnit * x.Quantity),
CurrentRevenue = revision.Current.Lines.Sum(x => x.PricePerUnit * x.Quantity)
}
});
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
Query = @"declare function isRevenueDeltaAboveThreshold(doc, threshold) {
return doc.Previous !== null && doc.Current.Lines.map(function(x) {
return x.PricePerUnit * x.Quantity;
}).reduce((a, b) => a + b, 0) > doc.Previous.Lines.map(function(x) {
return x.PricePerUnit * x.Quantity;
}).reduce((a, b) => a + b, 0) + threshold
}
from 'Orders' (Revisions = true) as doc
where isRevenueDeltaAboveThreshold(doc, 2500)
select {
PreviousRevenue: doc.Previous.Lines.map(function(x) {
return x.PricePerUnit * x.Quantity;
}).reduce((a, b) => a + b, 0),
CurrentRevenue: doc.Current.Lines.map(function(x) {
return x.PricePerUnit * x.Quantity;
}).reduce((a, b) => a + b, 0)
}"
});
The projection targets this class:
public class OrderRevenues
{
public decimal PreviousRevenue { get; set; }
public decimal CurrentRevenue { get; set; }
}
Example: Consuming the subscription
Because the revision fields are projected into OrderRevenues in the subscription's definition,
each batch item has the shape of that projected class rather than the default Result.Previous and
Result.Current fields shown in the
simple example.
SubscriptionWorker<OrderRevenues> revenuesComparisonWorker =
// Use the projected class type for the items the worker processes
store.Subscriptions.GetSubscriptionWorker<OrderRevenues>(subscriptionName);
await revenuesComparisonWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
Console.WriteLine($@"Revenue for order {item.Id}
grew from {item.Result.PreviousRevenue}
to {item.Result.CurrentRevenue}");
}
});
Including related documents
A revisions subscription can include related documents in the batches it sends (e.g., the Employee document that an order's
Employee field refers to), so the worker can read these documents without requesting them from the server.
The path of each include starts at the revision being processed (Current) or at the preceding revision (Previous), and ends at
the field that holds the ID of the document to include, e.g., Current.Employee (in RQL, after the query's alias:
doc.Current.Employee).
The worker reads an included document by loading the document in a session opened using batch.OpenSession.
To learn more about including related documents in batches, see
Example: Including documents in the batch.
When you use the include builder
with Revision<T>, pass each path to IncludeDocuments as a string.
e.g., IncludeDocuments("Current.Employee")
Example
In this example, the worker reports orders that were reassigned from one employee to another, and reads the names of both employees.
Creating the subscription
- Generic API
- RQL
subscriptionName = store.Subscriptions.Create(
new SubscriptionCreationOptions<Revision<Order>>()
{
// Include the employees that the processed revision and the preceding revision refer to
Includes = builder => builder
.IncludeDocuments("Current.Employee")
.IncludeDocuments("Previous.Employee")
});
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
// Include the employees that the processed revision and the preceding revision refer to
Query = @"from Orders (Revisions = true) as doc
include doc.Current.Employee, doc.Previous.Employee"
});
Consuming the subscription
SubscriptionWorker<Revision<Order>> worker =
store.Subscriptions.GetSubscriptionWorker<Revision<Order>>(subscriptionName);
await worker.Run(batch =>
{
// Open a session using 'batch.OpenSession' to access the included Employee documents
using (var session = batch.OpenSession())
{
foreach (var item in batch.Items)
{
var previousRevision = item.Result.Previous;
var currentRevision = item.Result.Current;
// Skip a document's first revision, the revision created when the document was deleted,
// and revisions that did not change the employee
if (previousRevision == null || currentRevision == null ||
previousRevision.Employee == currentRevision.Employee)
continue;
// Calling Load will not generate a request to the server,
// since both employees were included in the batch
var previousEmployee = session.Load<Employee>(previousRevision.Employee);
var currentEmployee = session.Load<Employee>(currentRevision.Employee);
Console.WriteLine($@"Order {item.Id} was reassigned from
{previousEmployee.FirstName} {previousEmployee.LastName}
to {currentEmployee.FirstName} {currentEmployee.LastName}");
}
}
});
Reading a revision's metadata
Each batch item of a revisions subscription holds two revisions of a document (Current and Previous).
The item's Metadata property and each revision's own metadata hold these kinds of metadata properties:
- Properties set by RavenDB (e.g.,
@idand@change-vector)
The item'sMetadataproperty holds a few of these properties for the item itself.
Each revision's metadata holds these properties for the revision. - Properties you set yourself (e.g.,
trace.id)
Only each revision's metadata holds these properties. The item'sMetadataproperty does not.
To read a revision's metadata, read the revision's @metadata object in the item's RawResult property,
which holds the item before deserialization to T.
The batch session does not track revisions, so GetMetadataFor cannot read a revision's metadata either.
e.g., the following worker reads the trace.id metadata property of each processed revision.
await worker.Run(batch =>
{
foreach (var item in batch.Items)
{
// Read a metadata property you set yourself from the revision being processed
if (item.RawResult.TryGet("Current", out BlittableJsonReaderObject currentRevision) &&
currentRevision != null &&
currentRevision.TryGet("@metadata", out BlittableJsonReaderObject metadata) &&
metadata.TryGet("trace.id", out string traceId))
{
// your processing logic here
}
}
});
Syntax
Classes
- Revision<T>
The processed-item type for a revisions subscription. Each batch item's Result is a
Revision<T> holding the revision being processed and the one before it.
public sealed class Revision<T> where T : class
{
public T Previous;
public T Current;
}
| Field | Type | Description |
|---|---|---|
| Previous | T | The preceding revision. null when Current is the document's first revision. |
| Current | T | The revision being processed. null for the revision created when the document is deleted. |