---
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: "python"
---

# Creating a data subscription: API

> Client language: Python. Also available for [C#](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.md), [Java](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.java.md), [Node.js](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.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**
>
> - 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)
>     - [Creating by document type or by a raw RQL query](#creating-by-document-type-or-by-a-raw-rql-query)
>     - [Creation methods vs update](#creation-methods-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_for_class` or
`store.subscriptions.create_for_options`.

### Creating by document type or by a raw RQL query

You can create a subscription using either of these methods:

- **By document type**  
  Pass the collection's document type to `create_for_class`, so the server sends the entire collection.
- **By a raw RQL (Raven Query Language) query**  
  Set the `query` string on `SubscriptionCreationOptions` and pass it to `create_for_options`, which
  lets you filter, project, and include.

The simplest definition sends an entire collection:

```python
# The server sends every document in the 'Orders' collection
# to any client that connects to this subscription.
name = store.subscriptions.create_for_class(Order)
```

### Creation methods vs `update`

- [create\_for\_class](#create_for_class) and [create\_for\_options](#create_for_options)
  are meant to be called **once** per subscription.
  - Calling either creation method **without providing a name** creates a **new** subscription.  
    The server sets the subscription's name to the subscription's ID.
  - Calling either creation method with a **new name** creates a subscription that carries this name.
  - Calling either creation method 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 `create_new` property of the [SubscriptionUpdateOptions](#classes)
  object you pass to `update`:

  - Set `create_new` 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 `create_new` 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).

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

```python
name = store.subscriptions.create_for_class(
    Order, SubscriptionCreationOptions(name="OrdersProcessingSubscription")
)
```

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 `mentor_node` property:

```python
name = store.subscriptions.create_for_class(
    # Make node D responsible for the subscription
    Order, SubscriptionCreationOptions(mentor_node="D")
)
```

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

## Starting point {#starting-point}

The `change_vector` property of the [subscription creation options](#classes) sets the point from which the
subscription starts sending documents to the worker.  
`change_vector` 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 `change_vector` 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.

```python
name = store.subscriptions.create_for_class(
    # Send only documents created or modified after the subscription's creation
    Order, SubscriptionCreationOptions(change_vector="LastDocument")
)
```

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, `key` and `create_new`:

- **`key`** targets the subscription by the ID the server assigned it at creation, instead of by
  name.
- **`create_new`** 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 `key` 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 `SubscriptionUpdateOptions` object keeps the subscription's current value.  
e.g., when you only change the query, the subscription keeps its name and processing progress:

```python
# Target the subscription by its key (the server-assigned ID) and change only its query
store.subscriptions.update(SubscriptionUpdateOptions(key=subscription_id, query="from Orders where Freight > 200"))
```

You can also move the subscription's [starting point](#starting-point) when you update it.  
Set `change_vector` 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 `create_new` 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 `change_vector` in the
  > options your application passes to `update`.  
  > A set `change_vector` counts as a change in the subscription's definition, so `update` moves the subscription's
  > [starting point](#starting-point) to the `change_vector` value each time the application starts.  
  > For example, with `change_vector` 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 either [create\_for\_class](#create_for_class) or [create\_for\_options](#create_for_options) rather than `update` when the application starts:
>
> - Passing the subscription's name to the method **would fail on every start after the first**, since the server attempts to create a subscription that already exists.
> - Not passing a name to the method **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.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.python.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.python.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 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`.

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders as o where o.'@metadata'.'Priority' = 'High'")
)
```

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.python.md#find-documents-that-are-missing-a-field)).

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        # A 'where' clause cannot start with 'not', so the clause starts with 'true and'
        query="from Orders as o where true and not exists(o.'@metadata'.'Priority')"
    )
)
```

---

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

   ```python
   store.subscriptions.create_for_options(
       SubscriptionCreationOptions(
           # A 'where' clause cannot start with 'not', so the clause starts with 'true and'
           query="from Emails as e where true and not exists(e.'@metadata'.'@refresh')"
       )
   )
   ```

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

   ```python
   with store.open_session() as session:
       email = Email(to="customer@example.com", subject="Your order has shipped")
       session.store(email)

       # Have the subscription send the email to the worker 7 days from now
       # (set the time as an ISO 8601 UTC date-time string)
       delivery_time = datetime.now(timezone.utc) + timedelta(days=7)
       session.advanced.get_metadata_for(email)["@refresh"] = delivery_time.isoformat()

       session.save_changes()
   ```

   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.

```python
def process_batch(batch):
    with batch.open_session() as session:
        for item in batch.items:
            # 'try_send_email' is your own function
            if not try_send_email(item.result):
                # Sending failed: have the subscription send the email again 10 minutes from now
                retry_time = datetime.now(timezone.utc) + timedelta(minutes=10)
                session.advanced.get_metadata_for(item.result)["@refresh"] = retry_time.isoformat()

        # Save the emails whose @refresh metadata property was set
        session.save_changes()
```

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:

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders as o select { Freight: o.Freight, ShipTo: o.ShipTo }")
)
```

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.python.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.python.md#classes)):

- The item's `result` property holds the projected object.
- The item's `key` property holds the ID of the document the projected object was created from (the **source document**).
- The item's `is_projection` property is `True`.
- The item's `metadata` 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.

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        # Include the source document's whole metadata, and a single metadata property
        query="""
        from Orders as o
        select {
            Freight: o.Freight,
            Metadata: getMetadata(o),
            TraceId: o['@metadata']['trace.id']
        }
        """
    )
)
```

---

#### Modifying source documents

A session that you open using the batch's `open_session` method
(see [Example: Processing documents in a session](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.python.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 `save_changes`.

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

```python
with batch.open_session() as session:
    for item in batch.items:
        # Load the source document of the projected object
        order = session.load(item.key, Order)
        # Set the field that the subscription's query uses to exclude handled orders
        order.ShippedAt = datetime.utcnow()

    # Save the modified source documents
    session.save_changes()
```

> **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:
>
> ```python
> name = store.subscriptions.create_for_options(
>     SubscriptionCreationOptions(query="from Orders as o where o.ShippedAt = null select { Freight: o.Freight }")
> )
> ```

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

A subscription you create using the Python client takes its handling of archived documents from 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.

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).

> **Note**
>
> On a [sharded database](https://docs.ravendb.net/7.2/sharding/subscriptions.md#unsupported-features), a subscription **ignores** 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

```python
name = store.subscriptions.create_for_class(Order)
```

#### RQL

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders")
)
```

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

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        declare function getOrderLinesSum(doc) {
            var sum = 0;
            for (var i in doc.Lines) {
                sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
            }
            return sum;
        }

        from Orders as o
        where getOrderLinesSum(o) > 100
        """
    )
)
```

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

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders where regex(ShipTo.City, '^New')")
)
```

### 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.python.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)).

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        from Orders as o
        where o.Freight > cmpxchg('config/minFreight')
        """
    )
)
```

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

```python
# Enable the document refresh feature for the database
store.maintenance.send(ConfigureRefreshOperation(RefreshConfiguration(disabled=False)))

# Create a subscription that selects only emails whose metadata does not hold the @refresh property
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        name="ScheduledEmails",
        # A 'where' clause cannot start with 'not', so the clause starts with 'true and'
        query="from Emails as e where true and not exists(e.'@metadata'.'@refresh')",
    )
)

# Store an email, and schedule its delivery to the worker 7 days from now
with store.open_session() as session:
    email = Email(to="customer@example.com", subject="Your order has shipped")
    session.store(email)
    delivery_time = datetime.now(timezone.utc) + timedelta(days=7)
    session.advanced.get_metadata_for(email)["@refresh"] = delivery_time.isoformat()
    session.save_changes()
```

#### Worker side

```python
worker = store.subscriptions.get_subscription_worker_by_name("ScheduledEmails", Email)

def process_batch(batch):
    with batch.open_session() as session:
        for item in batch.items:
            # 'try_send_email' is your own function
            if not try_send_email(item.result):
                # Sending failed: have the subscription send the email again 10 minutes from now
                retry_time = datetime.now(timezone.utc) + timedelta(minutes=10)
                session.advanced.get_metadata_for(item.result)["@refresh"] = retry_time.isoformat()

        # Save the emails whose @refresh metadata property was set
        session.save_changes()

worker.run(process_batch)
```

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

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        declare function getOrderLinesSum(doc) {
            var sum = 0;
            for (var i in doc.Lines) {
                sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
            }
            return sum;
        }

        declare function projectOrder(doc) {
            return {
                Id: id(doc),
                Total: getOrderLinesSum(doc)
            };
        }

        from Orders as o
        where getOrderLinesSum(o) > 100
        select projectOrder(o)
        """
    )
)
```

### 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.python.md#what-are-related-documents),
loaded using `load`.

```python
name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        declare function getOrderLinesSum(doc) {
            var sum = 0;
            for (var i in doc.Lines) {
                sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
            }
            return sum;
        }

        declare function projectOrder(doc) {
            var employee = load(doc.Employee);
            return {
                Id: id(doc),
                Total: getOrderLinesSum(doc),
                ShipTo: doc.ShipTo,
                EmployeeName: employee.FirstName + ' ' + employee.LastName
            };
        }

        from Orders as o
        where getOrderLinesSum(o) > 100
        select projectOrder(o)
        """
    )
)
```

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

#### Builder

```python
store.subscriptions.create_for_class(
    Order,
    # The documents whose IDs are in each order line's 'Product' property
    # will be included in the batch
    SubscriptionCreationOptions(includes=lambda builder: builder.include_documents("Lines[].Product")),
)
```

#### RQL path

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders include Lines[].Product")
)
```

#### RQL JavaScript

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        declare function includeProducts(doc) {
            let linesCount = doc.Lines.length;

            for (let i = 0; i < linesCount; i++) {
                include(doc.Lines[i].Product);
            }

            return doc;
        }

        from Orders as o select includeProducts(o)
        """
    )
)
```

To include related documents, assign a function to the `includes` property of the `SubscriptionCreationOptions` object.  
The function receives the include builder and calls the builder's `include_documents` method.  
Calls to the builder's methods can be chained.  
For the syntax of the builder's methods that include documents, see
[Include builder: documents](#include-builder-documents).

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:

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        from Orders as o
        select { Freight: o.Freight, Company: o.Company }
        include Company
        """
    )
)
```

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

```python
store.subscriptions.create_for_class(
    Order,
    # Values for the specified counters will be included in the batch
    SubscriptionCreationOptions(includes=lambda builder: builder.include_counters("Pros", "Cons")),
)
```

#### RQL

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders include counters('Pros'), counters('Cons')")
)
```

> **Info**
>
> To include counters using the builder, use Python client version 7.2.7 or later.

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.

```python
store.subscriptions.create_for_class(
    Order,
    SubscriptionCreationOptions(
        includes=lambda builder: builder
        .include_counter("Likes")
        .include_counters("Pros", "Cons")
        .include_documents("Employee")
    ),
)
```

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

```python
store.subscriptions.create_for_class(
    Order,
    SubscriptionCreationOptions(
        # Include the last 10 entries of each document's "HeartRate" time series
        includes=lambda builder: builder.include_time_series_by_range_type_and_count(
            "HeartRate", TimeSeriesRangeType.LAST, 10
        )
    ),
)
```

#### RQL

```python
store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders include timeseries('HeartRate', last(10))")
)
```

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":

```python
store.subscriptions.update(
    SubscriptionUpdateOptions(name="my subscription", query="from Products where PricePerUnit > 50")
)
```

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

```python
# Get the subscription's ID
my_subscription = store.subscriptions.get_subscription_state("my subscription")
subscription_id = my_subscription.subscription_id

# Update the subscription
store.subscriptions.update(
    SubscriptionUpdateOptions(key=subscription_id, query="from Products where PricePerUnit > 50")
)
```

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

```python
store.subscriptions.update(
    SubscriptionUpdateOptions(
        name="my subscription",
        query="from Products where PricePerUnit > 20",
        # Set to True so that a new subscription is created
        # if a subscription named "my subscription" does not exist
        create_new=True,
    )
)
```

## Syntax {#syntax}

### Methods

#### create

Create a subscription on the server.

##### create\_for\_options

```python
def create_for_options(self, options: SubscriptionCreationOptions,
                       database: Optional[str] = None) -> str: ...
```

##### create\_for\_class

```python
def create_for_class(self, object_type: Type[_T],
                     options: Optional[SubscriptionCreationOptions] = None,
                     database: Optional[str] = None) -> str: ...
```

| Parameter | Type | Description |
| - | - | - |
| **options** | `SubscriptionCreationOptions` | The subscription creation options. See the [Classes](#classes) below. |
| **object\_type** | `Type[_T]` | The document class whose collection the subscription draws from. |
| **database** | `str` | The database where the subscription is created. If `None`, the document store's default database is used. |

| Return value | |
| - | - |
| `str` | 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.

```python
def update(self, options: SubscriptionUpdateOptions,
           database: Optional[str] = None) -> str: ...
```

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

| Return value | |
| - | - |
| `str` | The name of the updated subscription. |

### Classes

#### SubscriptionCreationOptions

```python
class SubscriptionCreationOptions:
    def __init__(
        self,
        name: Optional[str] = None,
        query: Optional[str] = None,
        includes: Optional[Callable[[SubscriptionIncludeBuilder], None]] = None,
        change_vector: Optional[str] = None,
        mentor_node: Optional[str] = None,
    ): ...
```

#### SubscriptionUpdateOptions

```python
class SubscriptionUpdateOptions(SubscriptionCreationOptions):
    def __init__(
        self,
        name: Optional[str] = None,
        query: Optional[str] = None,
        includes: Optional[Callable[[SubscriptionIncludeBuilder], None]] = None,
        change_vector: Optional[str] = None,
        mentor_node: Optional[str] = None,
        key: Optional[int] = None,
        create_new: Optional[bool] = None,
    ): ...
```

| Property | Type | Description |
| - | - | - |
| **name** | `str` | A user-defined name for the subscription. Must be unique within the database. |
| **query** | `str` | An RQL query that defines the subscription.<br />See [Subscription query](#subscription-query). |
| **includes** | `Callable[[SubscriptionIncludeBuilder], None]` | 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. |
| **change\_vector** | `str` | A change vector marking where the subscription starts processing. See [Starting point](#starting-point). |
| **mentor\_node** | `str` | 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. |

The `SubscriptionUpdateOptions` class adds two properties to the creation options:

| Property | Type | Description |
| - | - | - |
| **key** | `int` | The ID the server assigned the subscription at creation. Retrieve it from the subscription's state. When updating, the `key` can be used instead of the `name` and takes precedence over it. |
| **create\_new** | `bool` | 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 assign to the `includes` property of a [SubscriptionCreationOptions](#classes) object
receives a `SubscriptionIncludeBuilder` object, whose methods add includes to the subscription.  
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

```python
# Include the documents whose IDs are held by the field at the given path
def include_documents(self, path: str) -> SubscriptionIncludeBuilder: ...
```

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

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

---

#### Include builder: counters

```python
# Include a single counter
def include_counter(self, name: str) -> SubscriptionIncludeBuilder: ...

# Include multiple counters
def include_counters(self, *names: str) -> SubscriptionIncludeBuilder: ...

# Include ALL counters from ALL documents that match the subscription criteria
def include_all_counters(self) -> SubscriptionIncludeBuilder: ...
```

| Parameter | Type | Description |
| - | - | - |
| **name** | `str` | The name of a counter. The subscription includes every counter with this name in the documents it retrieves. |
| **\*names** | `str` | Counter names. |

> **Info**
>
> To include counters using these methods, use Python client version 7.2.7 or later.

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

---

#### Include builder: time series

```python
# Include entries of a named time series, by a time range or by a number of entries
def include_time_series_by_range_type_and_time(self, name, ts_type, time) -> SubscriptionIncludeBuilder: ...
def include_time_series_by_range_type_and_count(self, name, ts_type, count) -> SubscriptionIncludeBuilder: ...

# Include all time series
def include_all_time_series_by_range_type_and_time(self, ts_type, time) -> SubscriptionIncludeBuilder: ...
def include_all_time_series_by_range_type_and_count(self, ts_type, count) -> SubscriptionIncludeBuilder: ...
```

| Parameter | Type | Description |
| - | - | - |
| **name** | `str` | The time series to include. |
| **ts\_type** | `TimeSeriesRangeType` | The range type, which must be `LAST`. |
| **time** | `TimeValue` | A time range to include. |
| **count** | `int` | A number of entries to include, counted from the most recent. |

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