---
title: "Creating a data subscription: API"
description: "Create and update RavenDB data subscriptions using the Client API, with filtering, projections, includes, and configurable subscription options."
url: "https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api"
version: "7.2"
language: "java"
---

# Creating a data subscription: API

> Client language: Java. Also available for [C#](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.md), [Node.js](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.nodejs.md), [Python](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.python.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**
>
> - A data subscription is a server-side task that sends documents matching a query to connected
>   clients ("workers"), in batches.
>
> - This page explains how to create and update a subscription using the Client API.  
>   You can also [create a subscription using Studio](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_studio.md).
>
> - A subscription's definition and its processing progress are kept on the cluster rather than on
>   a single node, and the cluster assigns one node to manage the task.
>
> - In this article:
>   - [Creating a subscription](#creating-a-subscription)
>     - [create with a document class or with a raw RQL query](#create-with-a-document-class-or-with-a-raw-rql-query)
>     - [create vs update](#create-vs-update)
>   - [Subscription name](#subscription-name)
>   - [Responsible node](#responsible-node)
>   - [Starting point](#starting-point)
>   - [Updating a subscription](#updating-a-subscription)
>     - [Changing a subscription's definition](#changing-a-subscriptions-definition)
>     - [Creating a subscription via update](#creating-a-subscription-via-update)
>   - [Subscription query](#subscription-query)
>     - [Supported query parts](#supported-query-parts)
>     - [Unsupported RQL features](#unsupported-rql-features)
>     - [Paths in a subscription query](#paths-in-a-subscription-query)
>     - [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)
>     - [Metadata in a subscription query](#metadata-in-a-subscription-query)
>   - [Projections](#projections)
>     - [Defining a projection](#defining-a-projection)
>     - [Processing projected objects](#processing-projected-objects)
>     - [Including documents with a projection](#including-documents-with-a-projection)
>   - [Archived documents](#archived-documents)
>   - [Examples](#examples)
>     - [Sending an entire collection](#example-sending-an-entire-collection)
>     - [Filtering documents](#example-filtering-documents)
>     - [Filtering with a regular expression](#example-filtering-with-a-regular-expression)
>     - [Filtering by a compare-exchange value](#example-filtering-by-a-compare-exchange-value)
>     - [Scheduling document delivery using the `@refresh` metadata property](#example-scheduling-document-delivery-using-the-refresh-metadata-property)
>     - [Filtering and projecting fields](#example-filtering-and-projecting-fields)
>     - [Projecting from a related document](#example-projecting-from-a-related-document)
>     - [Including documents](#example-including-documents)
>     - [Including documents with a projection](#example-including-documents-with-a-projection)
>     - [Including counters](#example-including-counters)
>     - [Including time series](#example-including-time-series)
>     - [Updating an existing subscription](#example-updating-an-existing-subscription)
>     - [Creating a subscription via update](#example-creating-a-subscription-via-update)
>   - [Syntax](#syntax)
>     - [Include builder](#include-builder)

## Creating a subscription {#creating-a-subscription}

To create a subscription, define the documents that the server should send to the worker, then register
this definition with the server using `store.subscriptions().create`.

### `create` with a document class or with a raw RQL query

You can use `create` in two ways:

- **By document class**  
  Pass the collection's document class (e.g., `Order.class`), so the server sends the entire collection.
- **By a raw RQL (Raven Query Language) query**  
  Set the `query` property of a [SubscriptionCreationOptions](#classes) object, which lets you filter, project, and include.

The simplest definition sends an entire collection:

```java
// The server sends every document in the 'Orders' collection
// to any client that connects to this subscription.
String subscriptionName = store.subscriptions().create(Order.class);
```

### `create` vs `update`

- [create](#create)
  is meant to be called **once** per subscription.
  - Calling `create` **without providing a name** creates a **new** subscription.  
    The server sets the subscription's name to the subscription's ID.
  - Calling `create` with a **new name** creates a subscription that carries this name.
  - Calling `create` with the name **of an existing subscription** throws an exception.

- [update](#update)
  is meant to **modify** an existing subscription's definition, but can also **create** a subscription.  
  The method's behavior depends on the `createNew` property of the [SubscriptionUpdateOptions](#classes)
  object you pass to `update`:

  - Set `createNew` to `true` to **create** the subscription if it doesn't exist yet,
    and **modify** the subscription if it already exists and its definition has changed.
  - Set `createNew` to `false` (the default) to **modify** an existing subscription.  
    If the subscription doesn't exist, `update` throws an exception.

  See [Creating a subscription via update](#creating-a-subscription-via-update).

---

For filtering and includes, see the [Examples](#examples) below.  
For projections, see [Projections](#projections).  
To subscribe to document revisions, see [Revisions support](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.java.md).

## Subscription name {#subscription-name}

Every subscription has a name, which clients use to identify the subscription they want to
consume.  
If you do not provide a name when creating the subscription, the server generates one for you.  
To set your own:

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Set a custom name for the subscription
options.setName("OrdersProcessingSubscription");

String subscriptionName = store.subscriptions().create(Order.class, options);
```

Setting your own name is useful for long-running batch processes: a readable name is easier to
work with in code, and you can reuse the same name across environments, as long as the
subscription is created in advance.

> **Info**
>
> A subscription name must be unique within its database. You cannot create two subscriptions with
> the same name in the same database.

## Responsible node {#responsible-node}

When a subscription is created, the cluster assigns one node to manage it. As long as this node is available,
it remains responsible for the subscription. If a worker connects to another node, that node will redirect it
to the responsible node.

If the responsible node goes down and your license includes
[highly available tasks](https://docs.ravendb.net/7.2/server/clustering/distribution/highly-available-tasks.md),
the task is reassigned to another node.  
While the assigned node is online, it remains the one managing the subscription.

To choose the responsible node yourself, set its tag in the `mentorNode` property:

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Make node D responsible for the subscription
options.setMentorNode("D");

String subscriptionName = store.subscriptions().create(Order.class, options);
```

Choosing the node manually lets you pick a server based on its hardware, proximity to the
consuming clients, or other considerations.

> **Note**
>
> To keep the subscription on the node you choose even if the node goes down, also set the `pinToMentorNode` property to `true`.  
> Pinning prevents another node from taking over the subscription, so processing resumes only when the chosen node
> is back online.

## Starting point {#starting-point}

The `changeVector` property of the [SubscriptionCreationOptions](#classes) object sets the point from which the
subscription starts sending documents to the worker.  
`changeVector` accepts these values:

- **`"BeginningOfTime"`**  
  The subscription sends all documents matching its query, regardless of their creation or modification time.  
  The subscription behaves the same way when `changeVector` is not set.
- **`"LastDocument"`**  
  The subscription sends only documents created or modified after the subscription's creation.  
  This is useful for an ad-hoc process that needs only recent changes.
- **An actual change vector**  
  The subscription starts from the point this change vector marks.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Send only documents created or modified after the subscription's creation
options.setChangeVector("LastDocument");

String subscriptionName = store.subscriptions().create(Order.class, options);
```

To change the starting point of an existing subscription, see [Updating a subscription](#updating-a-subscription).

## Updating a subscription {#updating-a-subscription}

### Changing a subscription's definition

You can change an existing subscription's definition using the [update](#update) method.  
Pass a [SubscriptionUpdateOptions](#classes) object, which extends the creation options with two
additional fields, `id` and `createNew`:

- **`id`** targets the subscription by the ID the server assigned it at creation, instead of by
  name.
- **`createNew`** applies when the subscription you are updating does not exist.  
  Set it to `true` to create the subscription instead, or leave it `false`, the default, to
  throw an exception.  
  See [Creating a subscription via update](#creating-a-subscription-via-update).

> **Note**
>
> You cannot rename a subscription by providing its `id` and a new `name`.  
> Doing this keeps the existing subscription under its current name and adds a second subscription with the new name and the same ID.

Any property you leave unset in the update options object keeps the subscription's current value, except `disabled` and
`pinToMentorNode` (see the note below).  
e.g., when you only change the query, the subscription keeps its name and processing progress:

```java
SubscriptionUpdateOptions updateOptions = new SubscriptionUpdateOptions();
// Target the subscription by its id and change only its query
updateOptions.setId(subscriptionId);
updateOptions.setQuery("from Orders where Freight > 200");

store.subscriptions().update(updateOptions);
```

> **Note**
>
> The `SubscriptionUpdateOptions` object always sends its `disabled` and `pinToMentorNode` properties to the server, and both
> properties are `false` unless you set them differently.  
> So unless you set these properties to the subscription's current values, `update` enables a disabled subscription, and a
> subscription pinned to its mentor node is no longer pinned.

You can also move the subscription's [starting point](#starting-point) when you update it.  
Set `changeVector` to `"BeginningOfTime"` to process all matching documents again, or to `"LastDocument"` to send only
documents created or modified after the update.

For a full update example, see the [Examples](#examples) below.

### Creating a subscription via update

Calling `update` for a subscription that does not exist throws an exception.  
If, however, the `createNew` property of the [SubscriptionUpdateOptions](#classes) object that you pass to `update` is set
to `true`, updating a subscription that does not exist creates the subscription using the name, query, and other options
set in the `SubscriptionUpdateOptions` object.

Creating a subscription via `update` is useful when your application defines a subscription and passes the definition to
`update` each time the application starts:

- The first time the application starts, `update` **creates** the subscription.
- On later starts, `update` **modifies** the subscription if the definition your application passes differs from the
  subscription's current definition (e.g., after you deploy a new version of the application with a changed query).  
  If there is no change in the subscription's definition, `update` leaves the subscription as it is.

  > **Info**
  >
  > To keep the subscription's processing progress when your application restarts, do not set `changeVector` in the
  > options your application passes to `update`.  
  > A set `changeVector` counts as a change in the subscription's definition, so `update` moves the subscription's
  > [starting point](#starting-point) to the `changeVector` value each time the application starts.  
  > For example, with `changeVector` set to `"BeginningOfTime"`, the subscription sends all matching documents again
  > each time the application starts.

See [Example: Creating a subscription via update](#example-creating-a-subscription-via-update).

---

> **Note**
>
> If your application calls [create](#create) rather than `update` when the application starts:
>
> - Passing the subscription's name to `create` **would fail on every start after the first**, since the server attempts to create a subscription that already exists.
> - Not passing a name to `create` **would create a new subscription on every start**, and each new subscription would send the matching documents from the beginning.

## Subscription query {#subscription-query}

Every subscription is ultimately expressed as an RQL statement.  
Although a subscription query has an RQL-like structure, it supports only the `declare`, `from`, `as`,
`load`, `where`, `select`, and `include` keywords.  
To create a subscription over document revisions, see
[Revisions support](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.java.md).

### Supported query parts

A subscription query can have these parts:

- **A `declare` functions section**, as in ordinary RQL.  
  These functions can hold any JavaScript code, and support `load` and `include` operations.
- **A `from` clause** naming the document source, for example `from Orders`.  
  This clause can address only a collection; indexes are not supported.
- **A `where` clause** deciding the documents the server sends to the worker.  
  This clause supports:
  - **Comparison operators**: `=`, `==`, `!=`, `<`, `>`, `<=`, `>=`
  - **Logical operators**: `and`, `or`, `and not`
  - **The `in` operator**, e.g., `o.Company in ('companies/1-A', 'companies/2-A')`
  - **Methods**:
    - `startsWith(field, prefix)`
    - `endsWith(field, suffix)`
    - `regex(field, pattern)`
    - `exists(field)`
    - `intersect(condition, condition, ...)`
  - **JavaScript**: plain JavaScript expressions and calls to declared functions, so you can express complex filtering.
- **A `select` clause** defining the [projection](#projections).  
  This clause can call functions, allowing complex transformations.
- **An `include` clause** defining documents (by path), counters, or time series to include.

To learn about the JavaScript that subscription functions can use, see [JavaScript engine](https://docs.ravendb.net/7.2/server/kb/javascript-engine.md).

### Unsupported RQL features

A subscription query does not support:

- The `order by`, `group by`, and `update` clauses.  
  `select distinct`.
- Querying an index. The `from` clause can name only a collection.
- The `search`, `boost`, `lucene`, `exact`, `moreLikeThis`, and `vector.search` methods.  
  Spatial methods.
- The `now()` and `today()` functions.
- The `between` operator. Use `>=` and `<=` instead.
- Query parameters (e.g., `$min`).
- Including any object other than documents, counters, or time series.  
  For example, [compare-exchange items](https://docs.ravendb.net/7.2/compare-exchange/overview.java.md) (`include cmpxchg(...)`) and revisions
  (`include revisions(...)`) cannot be included.

The subscription does not apply `limit` and `filter` clauses, although it accepts a query that includes them.

### Paths in a subscription query

Paths in a subscription query are handled as JavaScript expressions rather than as regular RQL
paths.  
A query that in RQL would be written as:

```sql
from Orders as o
where o.Lines[].Product = "products/1-A"
```

is written in a subscription query as follows:

```sql
declare function filterLines(doc, productId)
{
    if (!!doc.Lines){
        return doc.Lines.filter(x => x.Product == productId).length > 0;
    }
    return false;
}

from Orders as o
where filterLines(o, "products/1-A")
```

### Compare-exchange values in a subscription query

A subscription's query cannot take parameters, so a value that the query compares documents against (e.g., a minimum freight) is
normally written into the query itself.  
Changing such a value then means updating the subscription, and the server disconnects the workers connected to the subscription
when the query changes.  
To change the value without updating the subscription, keep the value in a [compare-exchange item](https://docs.ravendb.net/7.2/compare-exchange/overview.java.md)
and read it in the query using the `cmpxchg` function.

The server reads the compare-exchange value each time the server evaluates the subscription's query for a document, so a change
to the value applies only to documents evaluated after the change.  
A change to the value does not make the server evaluate the query again for documents that were already evaluated.  
e.g., after you lower a minimum freight, an order that did not exceed the old minimum is sent only when the order is modified.

See [Example: Filtering by a compare-exchange value](#example-filtering-by-a-compare-exchange-value).

### Metadata in a subscription query

A subscription query can read the [metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.java.md) of a document and
select documents by their metadata properties.  
e.g., the following subscription selects only orders whose metadata holds a `Priority` property with the value `High`.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders as o where o.'@metadata'.'Priority' = 'High'");

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

Changing a document's metadata changes the document, so if the changed document matches the subscription's query, the subscription
sends the document to the worker.

To select documents whose metadata does not hold a specific property, use `not exists`
(see [Find documents that are missing a field](https://docs.ravendb.net/7.2/querying/filtering-query-results/filter-by-field-presence.java.md#find-documents-that-are-missing-a-field)).

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// A 'where' clause cannot start with 'not', so the clause starts with 'true and'
options.setQuery("from Orders as o where true and not exists(o.'@metadata'.'Priority')");

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

---

#### Scheduling document delivery using the `@refresh` metadata property

To have a subscription send a document to the worker at a time you choose (e.g., an email that the worker should send next week):

1. **Enable the *document refresh* feature for the database.**  
   The *document refresh* feature removes the `@refresh` metadata property from a document
   once the time set by the property (e.g., `"@refresh": "2026-10-20T08:00:00.0000000Z"`) has passed, and saves the document.  
   To enable the *document refresh* feature, use the `ConfigureRefreshOperation` operation
   or Studio's [Document Refresh](https://docs.ravendb.net/7.2/documents/document-refresh/document-refresh-view.md) view.  
   The *document refresh* feature periodically checks the database for documents to refresh (every 60 seconds by default),
   so a document is refreshed at the first check after the time set by its `@refresh` metadata property.

   > **Note**
   >
   > On a [Community license](https://ravendb.net/buy), the *document refresh* feature cannot check for documents to refresh more
   > often than every 36 hours.

2. **Have your subscription select only documents whose metadata does not hold the `@refresh` property.**

   ```java
   SubscriptionCreationOptions options = new SubscriptionCreationOptions();
   // A 'where' clause cannot start with 'not', so the clause starts with 'true and'
   options.setQuery("from Emails as e where true and not exists(e.'@metadata'.'@refresh')");

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

3. **Store each document with its `@refresh` metadata property set to the intended delivery time.**

   ```java
   try (IDocumentSession session = store.openSession()) {
       Email email = new Email();
       email.setTo("customer@example.com");
       email.setSubject("Your order has shipped");
       session.store(email);

       // Have the subscription send the email to the worker 7 days from now
       Date deliveryTime = Date.from(Instant.now().plus(7, ChronoUnit.DAYS));
       session.advanced().getMetadataFor(email).put("@refresh", deliveryTime);

       session.saveChanges();
   }
   ```

   As long as the document's metadata holds the `@refresh` property, the document does not match the query, and the subscription
   does not send the document.  
   At the first check after the time set by the `@refresh` metadata property, the *document refresh* feature removes the property
   and saves the document.  
   The document then matches the query, and the subscription sends the document to the worker.

To have the subscription send a document to the worker again later (e.g., when the email server is unavailable and sending the email
fails), set a new time in the document's `@refresh` metadata property in the worker's batch-processing code, and save the document.  
The document then does not match the query until the *document refresh* feature removes the new `@refresh` metadata property.

```java
worker.run(batch -> {
    try (IDocumentSession session = batch.openSession()) {
        for (SubscriptionBatch.Item<Email> item : batch.getItems()) {
            // 'trySendEmail' is your own method
            if (!trySendEmail(item.getResult())) {
                // Sending failed: have the subscription send the email again 10 minutes from now
                Date retryTime = Date.from(Instant.now().plus(10, ChronoUnit.MINUTES));
                session.advanced().getMetadataFor(item.getResult()).put("@refresh", retryTime);
            }
        }

        // Save the emails whose @refresh metadata property was set
        session.saveChanges();
    }
});
```

See [Example: Scheduling document delivery using the `@refresh` metadata property](#example-scheduling-document-delivery-using-the-refresh-metadata-property).

## Projections {#projections}

### Defining a projection

By default, a subscription sends each matching document to a worker in full.  
To send only the data the worker needs (e.g., an order's freight and shipping address), define a projection.  
The subscription then creates, for each matching document, an object that holds only the data the projection defines, and sends
this object to the worker in place of the document.  
Using a projection to send only the needed data also keeps the rest of each document from reaching the worker (see
[Security considerations](https://docs.ravendb.net/7.2/data-subscriptions/overview.md#security-considerations)).

To define a projection, add a `select` clause to the subscription's query:

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders as o select { Freight: o.Freight, ShipTo: o.ShipTo }");

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

When you define a projection in a subscription's RQL query, the `select` clause must hold an object literal, as in the example
above, or a call to a declared function that returns the projected object (e.g., `select projectOrder(o)`).  
A list of fields, which ordinary RQL queries accept in a `select` clause (e.g., `select o.Freight, o.ShipTo`), will fail the
creation of the subscription.  
The `from` clause of a subscription query with a projection must define an alias for the collection (e.g., `from Orders as o`),
or the creation of the subscription will fail.

A projection can use:

- The document's fields, and values computed from these fields (e.g., an order's total).
- Data from [related documents](https://docs.ravendb.net/7.2/indexes/indexing-related-documents.java.md#what-are-related-documents), loaded using `load`.
- Counter values, using `counter` in RQL (e.g., `counter(o, 'Likes')`).
- Compare-exchange values, using `cmpxchg` in RQL
  (see [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)).

> **Note**
>
> For each document that matches the query's `where` clause, the server creates the projected object and sends the projected
> object to the worker.  
> If the projection returns `null` instead of an object, the server skips the document, as the server skips documents that do not
> match the `where` clause.  
> e.g., if the function you call in the `select` clause returns `null` for orders that have no `ShipTo` field, the worker does not
> receive these orders, although the orders match the `where` clause.

See [Example: Filtering and projecting fields](#example-filtering-and-projecting-fields) and
[Example: Projecting from a related document](#example-projecting-from-a-related-document).

### Processing projected objects

The subscription sends the projected objects to the worker in batches, and each item of a batch holds one projected object
(see the [batch item class](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.java.md#classes)):

- The item's `result` property holds the projected object.
- The item's `id` property holds the ID of the document the projected object was created from (the **source document**).
- The item's `projection` property is `true`.
- The item's `rawMetadata` property holds **the metadata of the projected object**, not the metadata of the source document.

To have the worker receive the metadata of the source document, include this metadata in the projection: use `getMetadata(o)` to
include the whole metadata, or `o['@metadata']['trace.id']` to include a single metadata property you set yourself (e.g., `trace.id`).  
In a `select` clause, write the metadata path using brackets, since the RQL form `o.'@metadata'.'trace.id'` will fail the creation of
the subscription.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Include the source document's whole metadata, and a single metadata property
options.setQuery(
    "from Orders as o\n" +
    "select {\n" +
    "    Freight: o.Freight,\n" +
    "    Metadata: getMetadata(o),\n" +
    "    TraceId: o['@metadata']['trace.id']\n" +
    "}");

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

---

#### Modifying source documents

A session that you open using the batch's `openSession` method
(see [Example: Processing documents in a session](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.java.md#example-processing-documents-in-a-session)) tracks the documents
the batch holds, but does not track projected objects.  
Changes you make to a projected object are therefore not saved when you call `saveChanges`.

To modify a source document, load the source document in the session using the item's `id`, change the loaded document,
and call `saveChanges`.  
Since the session does not hold the source document, loading the source document sends a request to the server.

```java
try (IDocumentSession session = batch.openSession()) {
    for (SubscriptionBatch.Item<ObjectNode> item : batch.getItems()) {
        // Load the source document of the projected object
        Order order = session.load(Order.class, item.getId());
        // Set the field that the subscription's query uses to exclude handled orders
        order.setShippedAt(new Date());
    }

    // Save the modified source documents
    session.saveChanges();
}
```

> **Note**
>
> Saving a modified source document makes the subscription send the document again if the document still matches the
> subscription's query (see [Processing order and re-sending](https://docs.ravendb.net/7.2/data-subscriptions/overview.md#processing-order-and-re-sending)).  
> To keep the worker from processing the same documents again, define the query to exclude the documents the worker has already
> handled.
>
> e.g., the sample above sets the `ShippedAt` field of each order the worker handles.  
> The following subscription selects only orders whose `ShippedAt` is `null`, so an order that the worker has saved with a
> shipping date no longer matches the subscription's query and is not sent again:
>
> ```java
> SubscriptionCreationOptions options = new SubscriptionCreationOptions();
> options.setQuery("from Orders as o where o.ShippedAt = null select { Freight: o.Freight }");
>
> String subscriptionName = store.subscriptions().create(options);
> ```

### Including documents with a projection

A subscription can include related documents in the batches it sends (e.g., the `Company` document that an order's `Company`
field refers to), so the worker can read these documents without requesting them from the server.  
When the subscription's query has a projection, the server looks for the fields that hold the IDs of the documents to include in
the projected object, not in the source document.  
The projection must therefore contain these fields (e.g., `Company`), or the subscription includes no documents.

See [Example: Including documents with a projection](#example-including-documents-with-a-projection).

## Archived documents {#archived-documents}

You can schedule documents to be [archived](https://docs.ravendb.net/7.2/data-archival/overview.md) (e.g., orders you no longer process regularly).  
RavenDB compresses archived documents to save disk space.  
By default, a subscription sends only non-archived documents to the worker.

To have the subscription send archived documents as well, or only archived documents, set the
`archivedDataProcessingBehavior` property of the [SubscriptionCreationOptions](#classes) object
when you create the subscription:

- **`EXCLUDE_ARCHIVED`**  
  The subscription selects only non-archived documents.
- **`INCLUDE_ARCHIVED`**  
  The subscription selects both archived and non-archived documents.  
  e.g., for a process that handles every order, including archived orders.
- **`ARCHIVED_ONLY`**  
  The subscription selects only archived documents.  
  e.g., for a process that copies archived orders to an external storage system.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Send only archived documents to the worker
options.setArchivedDataProcessingBehavior(ArchivedDataProcessingBehavior.ARCHIVED_ONLY);

String subscriptionName = store.subscriptions().create(Order.class, options);
```

If you leave `archivedDataProcessingBehavior` unset, the subscription uses the handling set by the
[Subscriptions.ArchivedDataProcessingBehavior](https://docs.ravendb.net/7.2/data-subscriptions/configuration.md#subscriptionsarchiveddataprocessingbehavior) configuration key (`ExcludeArchived` by default).  
The subscription keeps the key's value from the time the subscription is created, so a later change to the key
does not affect existing subscriptions.

> **Note**
>
> - The [update](#update) method does not change the subscription's handling of archived documents, even if you set
>   `archivedDataProcessingBehavior` in the update options object.  
>   To change an existing subscription's handling of archived documents, edit the subscription task in Studio's
>   [Ongoing Tasks view](https://docs.ravendb.net/7.2/studio/database/tasks/ongoing-tasks/general-info.md#the-ongoing-tasks-list), and set the task's **Archived Data Processing Behavior** option.  
>   This option is described in [Creating a data subscription: Studio](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_studio.md#defining-the-subscription-task).
> - A subscription to [document revisions](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.java.md) **ignores** `archivedDataProcessingBehavior` and sends the revisions of archived and non-archived documents alike.
> - On a [sharded database](https://docs.ravendb.net/7.2/sharding/subscriptions.md#unsupported-features), a subscription **ignores** both `archivedDataProcessingBehavior` and the
>   **Archived Data Processing Behavior** option set in Studio, and uses the handling set by the `Subscriptions.ArchivedDataProcessingBehavior` configuration key.  
>   Unlike on a non-sharded database, a later change to the configuration key **does** affect existing subscriptions.

To learn more about a subscription's handling of archived documents, see [Data archival: Archived documents and subscriptions](https://docs.ravendb.net/7.2/data-archival/archived-documents-and-other-features.md#archived-documents-and-subscriptions).

## Examples {#examples}

### Example: Sending an entire collection

In this example, the subscription sends to the worker every document in the `Orders` collection, with no filter or projection.

#### Generic API

```java
String subscriptionName = store.subscriptions().create(Order.class);
```

#### RQL

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

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

### Example: Filtering documents

In this example, the subscription sends to the worker only `Orders` whose total revenue exceeds 100.  
The server evaluates the filter and sends just the matching documents.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "declare function getOrderLinesSum(doc) {\n" +
    "    var sum = 0;\n" +
    "    for (var i in doc.Lines) {\n" +
    "        sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;\n" +
    "    }\n" +
    "    return sum;\n" +
    "}\n" +
    "\n" +
    "from Orders as o\n" +
    "where getOrderLinesSum(o) > 100");

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

### Example: Filtering with a regular expression

In this example, the subscription filters documents with a regular expression.  
Use the RQL `regex` function to match a field against a pattern on the server, here `Orders` whose
`ShipTo.City` starts with `New`.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders where regex(ShipTo.City, '^New')");

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

### Example: Filtering by a compare-exchange value

In this example, the subscription sends to the worker only `Orders` whose `Freight` exceeds the minimum freight kept in the
[compare-exchange item](https://docs.ravendb.net/7.2/compare-exchange/overview.java.md) `config/minFreight` (e.g., `100`).  
The query reads the item's value using the `cmpxchg` function (see [Compare-exchange values in a subscription query](#compare-exchange-values-in-a-subscription-query)).

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "from Orders as o\n" +
    "where o.Freight > cmpxchg('config/minFreight')");

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

### Example: Scheduling document delivery using the `@refresh` metadata property

In this example, the subscription sends each email to the worker once the time set in the email's `@refresh` metadata property has
passed, and the worker sets a new time in this property for each email the worker fails to send.  
For an explanation of this use of the `@refresh` metadata property, see
[Scheduling document delivery using the `@refresh` metadata property](#scheduling-document-delivery-using-the-refresh-metadata-property).

#### Subscription side

```java
// Enable the document refresh feature for the database
RefreshConfiguration refreshConfiguration = new RefreshConfiguration();
refreshConfiguration.setDisabled(false);
store.maintenance().send(new ConfigureRefreshOperation(refreshConfiguration));

// Create a subscription that selects only emails whose metadata does not hold the @refresh property
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setName("ScheduledEmails");
// A 'where' clause cannot start with 'not', so the clause starts with 'true and'
options.setQuery("from Emails as e where true and not exists(e.'@metadata'.'@refresh')");
store.subscriptions().create(options);

// Store an email, and schedule its delivery to the worker 7 days from now
try (IDocumentSession session = store.openSession()) {
    Email email = new Email();
    email.setTo("customer@example.com");
    email.setSubject("Your order has shipped");
    session.store(email);
    Date deliveryTime = Date.from(Instant.now().plus(7, ChronoUnit.DAYS));
    session.advanced().getMetadataFor(email).put("@refresh", deliveryTime);
    session.saveChanges();
}
```

#### Worker side

```java
SubscriptionWorker<Email> worker =
    store.subscriptions().getSubscriptionWorker(Email.class, "ScheduledEmails");

worker.run(batch -> {
    try (IDocumentSession session = batch.openSession()) {
        for (SubscriptionBatch.Item<Email> item : batch.getItems()) {
            // 'trySendEmail' is your own method
            if (!trySendEmail(item.getResult())) {
                // Sending failed: have the subscription send the email again 10 minutes from now
                Date retryTime = Date.from(Instant.now().plus(10, ChronoUnit.MINUTES));
                session.advanced().getMetadataFor(item.getResult()).put("@refresh", retryTime);
            }
        }

        // Save the emails whose @refresh metadata property was set
        session.saveChanges();
    }
});
```

### Example: Filtering and projecting fields

In this example, the subscription filters `Orders` by total revenue, and projects only two fields into each item
sent to the client: the document ID and the computed total.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "declare function getOrderLinesSum(doc) {\n" +
    "    var sum = 0;\n" +
    "    for (var i in doc.Lines) {\n" +
    "        sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;\n" +
    "    }\n" +
    "    return sum;\n" +
    "}\n" +
    "\n" +
    "declare function projectOrder(doc) {\n" +
    "    return {\n" +
    "        Id: id(doc),\n" +
    "        Total: getOrderLinesSum(doc)\n" +
    "    };\n" +
    "}\n" +
    "\n" +
    "from Orders as o\n" +
    "where getOrderLinesSum(o) > 100\n" +
    "select projectOrder(o)");

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

### Example: Projecting from a related document

In this example, the subscription projects fields from each `Order` and also pulls data from a
[related document](https://docs.ravendb.net/7.2/indexes/indexing-related-documents.java.md#what-are-related-documents),
loaded using `load`.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "declare function getOrderLinesSum(doc) {\n" +
    "    var sum = 0;\n" +
    "    for (var i in doc.Lines) {\n" +
    "        sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;\n" +
    "    }\n" +
    "    return sum;\n" +
    "}\n" +
    "\n" +
    "declare function projectOrder(doc) {\n" +
    "    var employee = load(doc.Employee);\n" +
    "    return {\n" +
    "        Id: id(doc),\n" +
    "        Total: getOrderLinesSum(doc),\n" +
    "        ShipTo: doc.ShipTo,\n" +
    "        EmployeeName: employee.FirstName + ' ' + employee.LastName\n" +
    "    };\n" +
    "}\n" +
    "\n" +
    "from Orders as o\n" +
    "where getOrderLinesSum(o) > 100\n" +
    "select projectOrder(o)");

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

### Example: Including documents

In this example, the subscription sends every `Order` and includes the `Product` documents related to the order
in the same batch, so the consuming worker can later read each `Product` without an extra call to
the server.

#### RQL path

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders include Lines[].Product");

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

#### RQL JavaScript

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "declare function includeProducts(doc) {\n" +
    "    let linesCount = doc.Lines.length;\n" +
    "\n" +
    "    for (let i = 0; i < linesCount; i++) {\n" +
    "        include(doc.Lines[i].Product);\n" +
    "    }\n" +
    "\n" +
    "    return doc;\n" +
    "}\n" +
    "\n" +
    "from Orders as o select includeProducts(o)");

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

In RQL, write the include in one of two ways: append the `include` keyword followed by the paths
to the fields holding the IDs to include (preferred, for both clarity and slightly better
performance), or call `include` inside a JavaScript function invoked from the `select` clause.

> **Info**
>
> When you include documents alongside a projection, the `include` resolves paths against the
> projected fields rather than the original document (see [Example: Including documents with a projection](#example-including-documents-with-a-projection)).

### Example: Including documents with a projection

In this example, the subscription sends a projection of each `Order` and includes the `Company` document related to the order
(see [Including documents with a projection](#including-documents-with-a-projection)).  
The projection contains the order's `Company` field, which holds the ID of the document to include:

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery(
    "from Orders as o\n" +
    "select { Freight: o.Freight, Company: o.Company }\n" +
    "include Company");

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

If the projection does not contain the `Company` field (e.g., `select { Freight: o.Freight }`), the subscription includes no
`Company` documents, even if the `include` clause names the field through the query's alias (`include o.Company`).

### Example: Including counters

In this example, the subscription sends to the worker every `Order` and includes the values of the
named counters in the batch.

#### Builder

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Values for the specified counters will be included in the batch
options.setIncludes(builder -> builder.includeCounters(new String[] { "Pros", "Cons" }));

String subscriptionName = store.subscriptions().create(Order.class, options);
```

#### RQL

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders include counters('Pros'), counters('Cons')");

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

For the syntax of the builder's methods that include counters, see
[Include builder: counters](#include-builder-counters).

Include builder methods can be **chained**.  
e.g., the following subscription includes several counters and a related document.

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setIncludes(builder -> builder
    .includeCounter("Likes")
    .includeCounters(new String[] { "Pros", "Cons" })
    .includeDocuments("Employee"));

String subscriptionName = store.subscriptions().create(Order.class, options);
```

> **Note**
>
> Changing the value of an existing counter after the document was sent does not trigger a
> re-send.  
> Adding a new counter to the document, or removing one, does trigger re-sending the document.

### Example: Including time series

In this example, the subscription sends every `Order` and includes time-series entries for each
document in the batch, so the worker has those entries without issuing additional requests to the server.

#### Builder

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
// Include the last 10 entries of each document's "HeartRate" time series
options.setIncludes(builder -> builder.includeTimeSeries("HeartRate", TimeSeriesRangeType.LAST, 10));

String subscriptionName = store.subscriptions().create(Order.class, options);
```

#### RQL

```java
SubscriptionCreationOptions options = new SubscriptionCreationOptions();
options.setQuery("from Orders include timeseries('HeartRate', last(10))");

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

In RQL, use the `last` method to define the entries to include: a number of the latest entries (e.g., `last(10)`), or a
period that ends at the time series' latest entry (e.g., `last(5, 'minutes')`).  
To include these entries from all of the document's time series, omit the time series name (e.g., `timeseries(last(10))`).  
A range defined by a start time and an end time is not supported.

For the syntax of the builder's methods that include time series, see
[Include builder: time series](#include-builder-time-series).

### Example: Updating an existing subscription

You can change a subscription's definition after creation. Target it by name, or by the ID the
server assigned it at creation.

Update by name, here changing the filter query of a subscription named "my subscription":

```java
SubscriptionUpdateOptions updateOptions = new SubscriptionUpdateOptions();
// Specify the subscription you wish to modify
updateOptions.setName("my subscription");

// Provide a new query
updateOptions.setQuery("from Products where PricePerUnit > 50");

String subscriptionName = store.subscriptions().update(updateOptions);
```

Update by ID, retrieving the ID from the subscription's state:

```java
// Get the subscription's ID
SubscriptionState mySubscription = store.subscriptions().getSubscriptionState("my subscription");
long subscriptionId = mySubscription.getSubscriptionId();

// Update the subscription
SubscriptionUpdateOptions updateOptions = new SubscriptionUpdateOptions();
updateOptions.setId(subscriptionId);
updateOptions.setQuery("from Products where PricePerUnit > 50");

String subscriptionName = store.subscriptions().update(updateOptions);
```

### Example: Creating a subscription via update

In this example, `update` creates a subscription named "my subscription" if the subscription does not exist yet, using the
query set in the `SubscriptionUpdateOptions` object.  
If the subscription already exists, `update` replaces the subscription's current query with the query set in
the `SubscriptionUpdateOptions` object, unless the two queries are the same.  
For an explanation of this use of `update`, see [Creating a subscription via update](#creating-a-subscription-via-update).

```java
SubscriptionUpdateOptions updateOptions = new SubscriptionUpdateOptions();
updateOptions.setName("my subscription");
updateOptions.setQuery("from Products where PricePerUnit > 20");

// Set to true so that a new subscription is created
// if a subscription named "my subscription" does not exist
updateOptions.setCreateNew(true);

String subscriptionName = store.subscriptions().update(updateOptions);
```

## Syntax {#syntax}

### Methods

#### create

##### create

Create a subscription on the server.

```java
// Overloads:
String create(SubscriptionCreationOptions options);
String create(SubscriptionCreationOptions options, String database);
<T> String create(Class<T> clazz);
<T> String create(Class<T> clazz, SubscriptionCreationOptions options);
<T> String create(Class<T> clazz, SubscriptionCreationOptions options, String database);
```

| Parameter | Type | Description |
| - | - | - |
| **options** | `SubscriptionCreationOptions` | The subscription creation options. See the [Classes](#classes) below. |
| **database** | `String` | The database where the subscription is created. If not specified, the document store's default database is used. |
| **clazz** | `Class<T>` | The document class whose collection the subscription draws from. |

| Return value | |
| - | - |
| `String` | The name of the created subscription. If a name was provided in the options it is returned; otherwise the server generates a unique name. |

#### update

##### update

Update an existing subscription's definition.

```java
// Overloads:
String update(SubscriptionUpdateOptions options);
String update(SubscriptionUpdateOptions options, String database);
```

| Parameter | Type | Description |
| - | - | - |
| **options** | `SubscriptionUpdateOptions` | The subscription update options. See the [Classes](#classes) below. |
| **database** | `String` | The database where the subscription resides. If not specified, the document store's default database is used. |

| Return value | |
| - | - |
| `String` | The name of the updated subscription.<br />If you target the subscription by `id` without setting `name`, and the subscription's definition does not change, `update` returns `null`. |

### Classes

#### SubscriptionCreationOptions

```java
public class SubscriptionCreationOptions {
    private String name;
    private String query;
    private Consumer<ISubscriptionIncludeBuilder> includes;
    private String changeVector;
    private String mentorNode;
    private boolean pinToMentorNode;
    private ArchivedDataProcessingBehavior archivedDataProcessingBehavior;
    private boolean disabled;

    // Getters and setters
}
```

#### SubscriptionUpdateOptions

```java
public class SubscriptionUpdateOptions extends SubscriptionCreationOptions {
    private Long id;
    private boolean createNew;

    // Getters and setters
}
```

| Property | Type | Description |
| - | - | - |
| **name** | `String` | A user-defined name for the subscription. Must be unique within the database. |
| **query** | `String` | An RQL query that defines the subscription.<br />See [Subscription query](#subscription-query). |
| **includes** | `Consumer<ISubscriptionIncludeBuilder>` | A function receiving an include builder, used to include related documents, counters, and time series in the batch. The [include methods](#include-builder) can be chained.<br />Applies only when you pass a document class to `create`. |
| **changeVector** | `String` | A change vector marking where the subscription starts processing. See [Starting point](#starting-point). |
| **mentorNode** | `String` | The tag of the node you want to handle the subscription. Useful when you prefer a specific server for its hardware, its proximity to clients, or other reasons. |
| **pinToMentorNode** | `boolean` | `true` keeps the subscription on the node set in `mentorNode`, even while that node is down.<br />See [Responsible node](#responsible-node). Default: `false`. |
| **archivedDataProcessingBehavior** | `ArchivedDataProcessingBehavior` | The subscription's handling of archived documents.<br />See [Archived documents](#archived-documents). |
| **disabled** | `boolean` | `true` creates the subscription disabled, so the subscription does not accept worker connections until you [enable it](https://docs.ravendb.net/7.2/data-subscriptions/maintenance-operations.java.md#enabling-and-disabling-a-subscription).<br />Default: `false`. |

`SubscriptionUpdateOptions` adds two properties to the creation options:

| Property | Type | Description |
| - | - | - |
| **id** | `Long` | The ID the server assigned the subscription at creation. Retrieve it from the subscription's state. When updating, the `id` can be used instead of the `name` and takes precedence over it. |
| **createNew** | `boolean` | What to do when the target subscription does not exist. `true` creates a new subscription from the provided options; `false` throws. Default: `false`. |

### Include builder

The function you pass to the `setIncludes` method of the [SubscriptionCreationOptions](#classes) object
receives the include builder, whose methods add includes to the subscription.  
The builder applies only when you also pass a document class to `create` (e.g., `create(Order.class, options)`).  
Calling `create` with the options object alone ignores the builder.  
Calls to the builder's methods can be chained.  
See, for instance, the chained calls in [Example: Including counters](#example-including-counters).

---

#### Include builder: documents

```java
// Include the documents whose IDs are held by the field at the given path
ISubscriptionIncludeBuilder includeDocuments(String path);
```

| Parameter | Type | Description |
| - | - | - |
| **path** | `String` | The path to the field holding the ID or IDs of the documents to include, e.g., `"Employee"`. |

See [Example: Including documents](#example-including-documents).

---

#### Include builder: counters

```java
// Include a single counter
ISubscriptionIncludeBuilder includeCounter(String name);

// Include multiple counters
ISubscriptionIncludeBuilder includeCounters(String[] names);

// Include ALL counters from ALL documents that match the subscription criteria
ISubscriptionIncludeBuilder includeAllCounters();
```

| Parameter | Type | Description |
| - | - | - |
| **name** | `String` | The name of a counter. The subscription includes every counter with this name in the documents it retrieves. |
| **names** | `String[]` | An array of counter names. |

See [Example: Including counters](#example-including-counters).

---

#### Include builder: time series

```java
// Include entries of a named time series, by a time range or by a number of entries
ISubscriptionIncludeBuilder includeTimeSeries(String name, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder includeTimeSeries(String name, TimeSeriesRangeType type, int count);

// The same, for several named time series
ISubscriptionIncludeBuilder includeTimeSeries(String[] names, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder includeTimeSeries(String[] names, TimeSeriesRangeType type, int count);

// Include all time series
ISubscriptionIncludeBuilder includeAllTimeSeries(TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder includeAllTimeSeries(TimeSeriesRangeType type, int count);
```

| Parameter | Type | Description |
| - | - | - |
| **name** / **names** | `String` / `String[]` | The time series to include. |
| **type** | `TimeSeriesRangeType` | The range type, which must be `TimeSeriesRangeType.LAST`. |
| **time** | `TimeValue` | A time range to include, for example `TimeValue.ofDays(7)`. |
| **count** | `int` | A number of entries to include, counted from the most recent. |

See [Example: Including time series](#example-including-time-series).
