---
title: "Data subscriptions: Revisions support"
description: "Subscribe to a collection's document revisions instead of its documents, so a worker receives consecutive revision pairs and can filter and project over the changes."
url: "https://docs.ravendb.net/7.2/data-subscriptions/revisions-support"
version: "7.2"
language: "java"
---

# Data subscriptions: Revisions support

> Client language: Java. Also available for [C#](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md), [Node.js](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - When the [Revisions feature](https://docs.ravendb.net/7.2/document-extensions/revisions/overview.md) 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, create the subscription using `createForRevisions`,
>   or add `(Revisions = true)` to the subscription's RQL query.
>
> - In this article:
>   - [Regular subscription vs revisions subscription](#regular-subscription-vs-revisions-subscription)
>   - [Revisions processing order](#revisions-processing-order)
>   - [Creating and consuming a revisions subscription](#creating-and-consuming-a-revisions-subscription)
>   - [Filtering revisions](#filtering-revisions)
>   - [Projecting fields from revisions](#projecting-fields-from-revisions)
>   - [Including related documents](#including-related-documents)
>   - [Reading a revision's metadata](#reading-a-revision-s-metadata)
>   - [Syntax](#syntax)

## Regular subscription vs revisions subscription {#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](#projecting-fields-from-revisions),
  each item in the batch contains both the processed revision (`getResult().getCurrent()`) and its
  preceding revision (`getResult().getPrevious()`).  
  One of the two fields is `null` in these cases:
  - For a document's first revision, `getPrevious()` is `null`.
  - For the revision created when the document is deleted, `getCurrent()` is `null`.

> **Warning**
>
> - For a revisions subscription to work, [Revisions must be configured](https://docs.ravendb.net/7.2/document-extensions/revisions/overview.md#defining-a-revisions-configuration)
>   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](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.java.md#archived-documents)
>   and selects the revisions of archived and non-archived documents alike.

## Revisions processing order {#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:

```json
{
    "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 {#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

```java
String name = store.subscriptions().createForRevisions(Order.class);
```

##### RQL

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders (Revisions = true)");

String name = store.subscriptions().createForRevisions(Order.class, options);
```

#### Example: Consuming the subscription

```java
SubscriptionWorker<Revision<Order>> revisionsWorker = store
    .subscriptions().getSubscriptionWorkerForRevisions(Order.class, name);

revisionsWorker.run(x -> {
    for (SubscriptionBatch.Item<Revision<Order>> item : x.getItems()) {
        // The preceding revision (null for a document's first revision)
        Order previousRevision = item.getResult().getPrevious();

        // The revision being processed
        Order currentRevision = item.getResult().getCurrent();

        processOrderRevisions(previousRevision, currentRevision); // your processing logic
    }
});
```

## Filtering revisions {#filtering-revisions}

This subscription sends to the worker only the revisions in which the order was shipped to Mexico.

#### Example: Creating the subscription

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Only revisions of orders shipped to Mexico are sent to the worker
options.setQuery(
    "declare function isSentToMexico(doc) {\n" +
    "    return doc.Current.ShipTo.Country == 'Mexico'\n" +
    "}\n" +
    "\n" +
    "from 'Orders' (Revisions = true) as doc\n" +
    "where isSentToMexico(doc) == true");

String name = store.subscriptions().create(options);
```

#### Example: Consuming the subscription

```java
SubscriptionWorker<Revision<Order>> worker = store
    .subscriptions().getSubscriptionWorkerForRevisions(Order.class, name);

worker.run(batch -> {
    for (SubscriptionBatch.Item<Revision<Order>> item : batch.getItems()) {
        System.out.printf("This is a revision of document %s.%n" +
            "The order in this revision was shipped at %s.%n",
            item.getId(), item.getResult().getCurrent().getShippedAt());
    }
});
```

## Projecting fields from revisions {#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

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "declare function isRevenueDeltaAboveThreshold(doc, threshold) {\n" +
    "    return doc.Previous !== null && doc.Current.Lines.map(function(x) {\n" +
    "        return x.PricePerUnit * x.Quantity;\n" +
    "    }).reduce((a, b) => a + b, 0) > doc.Previous.Lines.map(function(x) {\n" +
    "        return x.PricePerUnit * x.Quantity;\n" +
    "    }).reduce((a, b) => a + b, 0) + threshold\n" +
    "}\n" +
    "from 'Orders' (Revisions = true) as doc\n" +
    "where isRevenueDeltaAboveThreshold(doc, 2500)\n" +
    "select {\n" +
    "    previousRevenue: doc.Previous.Lines.map(function(x) {\n" +
    "        return x.PricePerUnit * x.Quantity;\n" +
    "    }).reduce((a, b) => a + b, 0),\n" +
    "    currentRevenue: doc.Current.Lines.map(function(x) {\n" +
    "        return x.PricePerUnit * x.Quantity;\n" +
    "    }).reduce((a, b) => a + b, 0)\n" +
    "}");

String name = store.subscriptions().create(options);
```

The projection targets this class:

```java
public class OrderRevenues {
    private double previousRevenue;
    private double currentRevenue;

    public double getPreviousRevenue() {
        return previousRevenue;
    }

    public void setPreviousRevenue(double previousRevenue) {
        this.previousRevenue = previousRevenue;
    }

    public double getCurrentRevenue() {
        return currentRevenue;
    }

    public void setCurrentRevenue(double currentRevenue) {
        this.currentRevenue = currentRevenue;
    }
}
```

#### 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 `getPrevious()` and
`getCurrent()` fields shown in the
[simple example](#creating-and-consuming-a-revisions-subscription).

```java
SubscriptionWorker<OrderRevenues> revenuesComparisonWorker = store
    // Use the projected class type for the items the worker processes
    .subscriptions().getSubscriptionWorker(OrderRevenues.class, name);

revenuesComparisonWorker.run(x -> {
    for (SubscriptionBatch.Item<OrderRevenues> item : x.getItems()) {
        OrderRevenues revenues = item.getResult();

        System.out.printf("Revenue for order %s grew from %f to %f%n",
            item.getId(), revenues.getPreviousRevenue(), revenues.getCurrentRevenue());
    }
});
```

## Including related documents {#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., `doc.Current.Employee` (where `doc` is the query's alias).  
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](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.java.md#example-including-documents-in-the-batch).

### 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

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Include the employees that the processed revision and the preceding revision refer to
options.setQuery(
    "from Orders (Revisions = true) as doc\n" +
    "include doc.Current.Employee, doc.Previous.Employee");

String name = store.subscriptions().create(options);
```

#### Consuming the subscription

```java
SubscriptionWorker<Revision<Order>> worker = store
    .subscriptions().getSubscriptionWorkerForRevisions(Order.class, name);

worker.run(batch -> {
    // Open a session using 'batch.openSession' to access the included Employee documents
    try (IDocumentSession session = batch.openSession()) {
        for (SubscriptionBatch.Item<Revision<Order>> item : batch.getItems()) {
            Order previousRevision = item.getResult().getPrevious();
            Order currentRevision = item.getResult().getCurrent();

            // 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.getEmployee().equals(currentRevision.getEmployee())) {
                continue;
            }

            // Calling load will not generate a request to the server,
            // since both employees were included in the batch
            Employee previousEmployee = session.load(Employee.class, previousRevision.getEmployee());
            Employee currentEmployee = session.load(Employee.class, currentRevision.getEmployee());

            System.out.printf("Order %s was reassigned from %s %s to %s %s%n", item.getId(),
                previousEmployee.getFirstName(), previousEmployee.getLastName(),
                currentEmployee.getFirstName(), currentEmployee.getLastName());
        }
    }
});
```

## Reading a revision's metadata {#reading-a-revision-s-metadata}

Each batch item of a revisions subscription holds two revisions of a document (`getCurrent()` and `getPrevious()`).  
The item's `metadata` property and each revision's own metadata hold these kinds of metadata properties:

- **Properties set by RavenDB** (e.g., `@id` and `@change-vector`)  
  The item's `metadata` property 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's `metadata` property does not.

To read a revision's metadata, read the revision's `@metadata` object in the item's `rawResult` property (`getRawResult()`),
which holds the item before deserialization to `T`.

e.g., the following worker reads the `trace.id` metadata property of each processed revision.

```java
worker.run(batch -> {
    for (SubscriptionBatch.Item<Revision<Order>> item : batch.getItems()) {
        // Read a metadata property you set yourself from the revision being processed
        JsonNode traceId = item.getRawResult().path("Current").path("@metadata").get("trace.id");
        if (traceId != null) {
            // your processing logic here
        }
    }
});
```

## Syntax {#syntax}

### Classes

The processed-item type for a revisions subscription. Each batch item's `getResult()` returns a
`Revision<T>` holding the revision being processed and the one before it.

```java
public class Revision<T> {
    public T getPrevious();
    public T getCurrent();
}
```

| Method | Return type | Description |
| - | - | - |
| **getPrevious()** | `T` | The preceding revision. `null` when `getCurrent()` returns the document's first revision. |
| **getCurrent()** | `T` | The revision being processed. `null` for the revision created when the document is deleted. |
