Skip to main content

Creating a data subscription: API

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 or its asynchronous counterpart, store.Subscriptions.CreateAsync.

Create and CreateAsync​

Create and CreateAsync take the same arguments and an optional cancellation token.
The examples on this page call Create. To create a subscription asynchronously, await CreateAsync.

// The server sends every document in the 'Orders' collection
// to any client that connects to this subscription.
subscriptionName = store.Subscriptions.Create<Order>();

Create with typed expressions or with a raw RQL query​

You can use Create in two ways:

  • Typed expressions
    Write the definition as C# expressions, in one of these forms:

    • Pass a SubscriptionCreationOptions<T> object whose Filter, Projection, and Includes expressions define the subscription.

      subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
      {
      Filter = x => x.Freight > 100
      });
    • Pass a lambda predicate directly to Create<T>.

      subscriptionName = store.Subscriptions.Create<Order>(x => x.Freight > 100);
  • A raw RQL (Raven Query Language) query
    Set the Query string in a SubscriptionCreationOptions object.

    subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
    {
    Query = "from Orders where Freight > 100"
    });

Create vs Update​

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


For filtering and includes, see the Examples below.
For projections, see Projections.
To subscribe to document revisions, see Revisions support.

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:

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>
{
// Set a custom name for the subscription
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.

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

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

subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
// Make node D responsible for the subscription
MentorNode = "D"
});

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

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​

The ChangeVector property of the subscription creation options 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.
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
// Send only documents created or modified after the subscription's creation
ChangeVector = "LastDocument"
});

To change the starting point of an existing subscription, see Updating a subscription.

Updating a subscription​

Changing a subscription's definition​

You can change an existing subscription's definition using the Update method or its asynchronous counterpart, UpdateAsync.
Pass a SubscriptionUpdateOptions 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.

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 SubscriptionUpdateOptions object keeps the subscription's current value.
e.g., when you only change the query, the subscription keeps its name and processing progress:

// Target the subscription by its Id and change only its query
store.Subscriptions.Update(new SubscriptionUpdateOptions
{
Id = subscriptionId,
Query = "from Orders where Freight > 200"
});

You can also move the subscription's 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 below.

Updating a subscription defined using typed expressions​

The Update method described above accepts a subscription's definition only as an RQL query, not as typed expressions.
To update a subscription you defined using a SubscriptionCreationOptions<T> object, call the object's ToSubscriptionCreationOptions method.
This method translates the object's Filter, Projection, and Includes expressions into an RQL query, and returns the query in the Query property of a SubscriptionCreationOptions object.
Pass the translated query to Update:

var typedOptions = new SubscriptionCreationOptions<Order>
{
Name = "OrdersProcessingSubscription",
// The changed filter
Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 200
};

// Translate the typed expressions into an RQL query, using the store's conventions
SubscriptionCreationOptions translated = typedOptions.ToSubscriptionCreationOptions(store.Conventions);

// Update the subscription with the translated query
store.Subscriptions.Update(new SubscriptionUpdateOptions
{
Name = translated.Name,
Query = translated.Query
});

Using the translated query, you can also check whether your typed expressions still match the subscription's current definition (e.g., after you change a filter in your code), as shown in the example 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 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.

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


If your application calls 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​

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.

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

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

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

is written in a subscription query as follows:

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

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.

subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
{
Query = "from Orders as o where o.'@metadata'.'Priority' = 'High'"
});

Typed expressions cannot read a document's metadata, so metadata conditions can only be written in a raw RQL query.

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

subscriptionName = store.Subscriptions.Create(new 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 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.


    On a Community license, 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.

    subscriptionName = store.Subscriptions.Create(new 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.

    using (var session = store.OpenSession())
    {
    var email = new 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
    session.Advanced.GetMetadataFor(email)["@refresh"] = DateTime.UtcNow.AddDays(7);

    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.

using (var session = batch.OpenSession())
{
foreach (var item in batch.Items)
{
// 'TrySendEmail' is your own method
if (TrySendEmail(item.Result) == false)
{
// Sending failed: have the subscription send the email again 10 minutes from now
session.Advanced.GetMetadataFor(item.Result)["@refresh"] = DateTime.UtcNow.AddMinutes(10);
}
}

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

See Example: Scheduling document delivery using the @refresh metadata property.

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

You can define a projection in two ways:

  • A raw RQL query
    Add a select clause to the subscription's query.

    subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
    {
    Query = "from Orders as o select { Freight: o.Freight, ShipTo: o.ShipTo }"
    });

    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.

  • Typed expressions
    Set the Projection expression of a SubscriptionCreationOptions<T> object.

    subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
    {
    Projection = x => new { x.Freight, x.ShipTo }
    });

    The client translates the Projection expression into the select clause of the subscription's query, and writes the object literal and the alias for you, so the subscription's query meets the select and alias rules described above.

A projection can use:

  • The document's fields, and values computed from these fields (e.g., an order's total).
  • Data from related documents, loaded using RavenQuery.Load in a typed expression, or using load in RQL.
  • 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).

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 and 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 SubscriptionBatch<T>.Item):

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

subscriptionName = store.Subscriptions.Create(new 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']
}"
});

Typed expressions cannot read a document's metadata, so a projection that includes metadata can only be written in a raw RQL query.


Modifying source documents​

A session that you open using the batch's OpenSession method (see 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.

using (var session = batch.OpenSession())
{
foreach (var item in batch.Items)
{
// Load the source document of the projected object
var order = session.Load<Order>(item.Id);
// Set the field that the subscription's query uses to exclude handled orders
order.ShippedAt = DateTime.UtcNow;
}

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

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

subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions
{
Query = "from Orders as o where o.ShippedAt = null select { Freight: o.Freight }"
});

Projecting into your own class or record​

The Projection expression of a SubscriptionCreationOptions<T> object can create an anonymous object, or an object of a class or record you define (e.g., OrderTotal).
To have the worker receive the projected items as objects of this class or record, pass the class or record as the type parameter of GetSubscriptionWorker when you create the worker (e.g., GetSubscriptionWorker<OrderTotal>).

Projecting into a class or record you define has two advantages over projecting into an anonymous object:

  • Field names checked when you build the application
    The C# compiler checks the worker's use of the projected fields (e.g., orderTotal.Total), so a misspelled field name is reported when you build the application.
    If the projection creates an anonymous object, the worker can receive the projected items as dynamic objects, whose field names the C# compiler cannot check, so a misspelled field name is found only when the code runs.
  • One definition for the projection and the worker
    The projection and the worker both use the class or record, so the projected fields are defined in one place.
    With an anonymous object in the projection, a class of your own for the worker (e.g., GetSubscriptionWorker<OrderSummary>) defines the fields a second time, so every change must be made in both definitions.

Creating the object in the projection​

To create an object of a class or record you define, use an object initializer, or call a constructor.
When you call a constructor, each of its parameters must have the name of a public property of the class or record (case is ignored) and a type compatible with the property's type.
The client names the fields of the projected object after these properties.

e.g., the constructor parameters of the following class match the class's properties, so a projection can create objects of the class by calling the constructor:

public class OrderInfo
{
// The 'orderId' parameter matches the 'OrderId' property (case is ignored)
public OrderInfo(string orderId, decimal freight)
{
OrderId = orderId;
Freight = freight;
}

public string OrderId { get; }
public decimal Freight { get; }
}

subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
// Create the projected object by calling the constructor
Projection = x => new OrderInfo(x.Id, x.Freight)
});

The projected object holds the fields OrderId and Freight.

A positional record (a record whose properties are defined by its constructor's parameters) can be created only by calling the record's constructor, and the record's parameters always match its properties.

See Example: Projecting into a record.

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.

Archived documents​

You can schedule documents to be archived (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 subscription creation options when you create the subscription:

  • ExcludeArchived
    The subscription selects only non-archived documents.
  • IncludeArchived
    The subscription selects both archived and non-archived documents.
    e.g., for a process that handles every order, including archived orders.
  • ArchivedOnly
    The subscription selects only archived documents.
    e.g., for a process that copies archived orders to an external storage system.
subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
// Send only archived documents to the worker
ArchivedDataProcessingBehavior = ArchivedDataProcessingBehavior.ArchivedOnly
});

If you leave ArchivedDataProcessingBehavior unset, the subscription uses the handling set by the Subscriptions.ArchivedDataProcessingBehavior 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.

  • The Update method does not change the subscription's handling of archived documents, even if you set ArchivedDataProcessingBehavior in the SubscriptionUpdateOptions object.
    To change an existing subscription's handling of archived documents, edit the subscription task in Studio's Ongoing Tasks view, and set the task's Archived Data Processing Behavior option.
    This option is described in Creating a data subscription: Studio.
  • A subscription to document revisions ignores ArchivedDataProcessingBehavior and sends the revisions of archived and non-archived documents alike.
  • On a sharded database, 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.

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.

subscriptionName = store.Subscriptions.Create<Order>();

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.

subscriptionName = store.Subscriptions.Create<Order>(x =>
// Only documents matching this filter will be sent
x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100);

Example: Filtering with a regular expression​

In this example, the subscription filters documents with a regular expression.
Use Regex.IsMatch inside the filter expression to match a field against a pattern on the server, here Orders whose ShipTo.City starts with New.

// Filter using Regex.IsMatch in the subscription's LINQ filter
subscriptionName = store.Subscriptions.Create<Order>(x =>
Regex.IsMatch(x.ShipTo.City, "^New"));

Pass supported RegexOptions as a third argument:

// Filter with case-insensitive regex matching
subscriptionName = store.Subscriptions.Create<Order>(x =>
Regex.IsMatch(x.ShipTo.City, "^new", RegexOptions.IgnoreCase));

The following RegexOptions are supported: RegexOptions.IgnoreCase, RegexOptions.Multiline, and RegexOptions.Singleline.
Other values, such as Compiled or ExplicitCapture, and the timeout overload are not supported and throw a NotSupportedException.
The pattern must be a constant expression; it cannot be a value computed at runtime from document fields.

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 config/minFreight (e.g., 100).
The query reads the item's value using the cmpxchg function (see Compare-exchange values in a subscription query).

subscriptionName = store.Subscriptions.Create(new 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.

Subscription side​

// Enable the document refresh feature for the database
store.Maintenance.Send(new ConfigureRefreshOperation(new RefreshConfiguration
{
Disabled = false
}));

// Create a subscription that selects only emails whose metadata does not hold the @refresh property
store.Subscriptions.Create(new 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
using (var session = store.OpenSession())
{
var email = new Email { To = "customer@example.com", Subject = "Your order has shipped" };
session.Store(email);
session.Advanced.GetMetadataFor(email)["@refresh"] = DateTime.UtcNow.AddDays(7);
session.SaveChanges();
}

Worker side​

var worker = store.Subscriptions.GetSubscriptionWorker<Email>("ScheduledEmails");

await worker.Run(batch =>
{
using (var session = batch.OpenSession())
{
foreach (var item in batch.Items)
{
// 'TrySendEmail' is your own method
if (TrySendEmail(item.Result) == false)
{
// Sending failed: have the subscription send the email again 10 minutes from now
session.Advanced.GetMetadataFor(item.Result)["@refresh"] = DateTime.UtcNow.AddMinutes(10);
}
}

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

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
// The subscription criteria:
Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

// The object properties that will be sent for each matching document:
Projection = x => new
{
Id = x.Id,
Total = x.Lines.Sum(line => line.PricePerUnit * line.Quantity)
}
});

Example: Projecting into a record​

In this example, the subscription projects each Order into an OrderTotal positional record by calling the record's constructor, and the worker receives each projected item as an OrderTotal object (see Projecting into your own class or record).

// A positional record: its parameters define both its constructor
// and its properties, which are the projected fields
public record OrderTotal(string OrderId, decimal Total);

subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

// Create the projected object using the record's constructor
Projection = x => new OrderTotal(x.Id, x.Lines.Sum(line => line.PricePerUnit * line.Quantity))
});

// Get a worker that receives the projected items as OrderTotal objects
SubscriptionWorker<OrderTotal> worker = store.Subscriptions.GetSubscriptionWorker<OrderTotal>(subscriptionName);

var subscriptionRuntimeTask = worker.Run(batch =>
{
foreach (var item in batch.Items)
{
OrderTotal orderTotal = item.Result;
Console.WriteLine($"{orderTotal.OrderId}: {orderTotal.Total}");
}
});

In this example, the subscription projects fields from each Order and also pulls data from a related document, loaded using Load.

subscriptionName = store.Subscriptions.Create<Order>(
new SubscriptionCreationOptions<Order>()
{
// The subscription criteria:
Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 100,

// The object properties that will be sent for each matching document:
Projection = x => new
{
Id = x.Id,
Total = x.Lines.Sum(line => line.PricePerUnit * line.Quantity),
ShipTo = x.ShipTo,

// 'Load' the related Employee document and use its data in the projection
// Both Load calls resolve to a single server-side load
EmployeeName = RavenQuery.Load<Employee>(x.Employee).FirstName + " " +
RavenQuery.Load<Employee>(x.Employee).LastName
}
});

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.

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
Includes = builder => builder
// The documents whose IDs are in each order line's 'Product' property
// will be included in the batch
.IncludeDocuments(x => x.Lines.Select(y => y.Product))
});

To include related documents, assign a function to the Includes property of the SubscriptionCreationOptions<T> object.
The function receives an ISubscriptionIncludeBuilder object and calls the builder's IncludeDocuments 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.

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.

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​

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).
The projection contains the order's Company field, which holds the ID of the document to include:

subscriptionName = store.Subscriptions.Create(new 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.

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
Includes = builder => builder
// Values for the specified counters will be included in the batch
.IncludeCounters(new[] { "Pros", "Cons" })
});

For the syntax of the builder's methods that include counters, see Include builder: counters.

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

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
Includes = builder => builder
.IncludeCounter("Likes")
.IncludeCounters(new[] { "Pros", "Cons" })
.IncludeDocuments("Employee")
});

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.

subscriptionName = store.Subscriptions.Create<Order>(new SubscriptionCreationOptions<Order>()
{
Includes = builder => builder
// Include the last 10 entries of each document's "HeartRate" time series
.IncludeTimeSeries("HeartRate", TimeSeriesRangeType.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.

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

subscriptionName = store.Subscriptions.Update(new SubscriptionUpdateOptions()
{
// Specify the subscription you wish to modify
Name = "my subscription",

// Provide a new query
Query = "from Products where PricePerUnit > 50"
});

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

// Get the subscription's ID
SubscriptionState mySubscription = store.Subscriptions.GetSubscriptionState("my subscription");
long subscriptionId = mySubscription.SubscriptionId;

// Update the subscription
subscriptionName = store.Subscriptions.Update(new SubscriptionUpdateOptions()
{
Id = subscriptionId,
Query = "from Products where PricePerUnit > 50"
});

Example: Updating a subscription defined using typed expressions​

In this example, the application compares the RQL query translated from its typed expressions with the subscription's current query, and updates the subscription only if the two queries differ.
The application retrieves the current query from the server using GetSubscriptionState.
An application can run this check at startup, e.g., after a new version of the application has changed the subscription's filter.

// The subscription's definition, as the application's code defines it now
var typedOptions = new SubscriptionCreationOptions<Order>
{
Name = "OrdersProcessingSubscription",
Filter = x => x.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 200
};

// Translate the typed expressions into an RQL query, using the store's conventions
SubscriptionCreationOptions translated = typedOptions.ToSubscriptionCreationOptions(store.Conventions);

// Get the subscription's current query from the server
SubscriptionState state = store.Subscriptions.GetSubscriptionState(translated.Name);

// Update the subscription only if its current query differs from the translated query
if (state.Query != translated.Query)
{
store.Subscriptions.Update(new SubscriptionUpdateOptions
{
Name = translated.Name,
Query = translated.Query
});
}

When the typed expressions include a filter, a projection, or includes, the translated query spans several lines, and the characters that end each line (the line breaks) follow the format of the operating system that runs the translation (\r\n on Windows, \n on Linux).
If the subscription's current query was translated on another operating system, the two queries differ in their line breaks even when the typed expressions are the same, so the subscription is updated although its definition has not changed.
The server then disconnects the workers connected to the subscription, and the workers reconnect to it.
The subscription keeps its processing progress.
To avoid an unneeded update, compare the queries with their line breaks normalized:

if (state.Query.Replace("\r\n", "\n") != translated.Query.Replace("\r\n", "\n"))

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.

subscriptionName = store.Subscriptions.Update(new 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
CreateNew = true
});

Syntax​

Methods​

Create​

Create a subscription on the server.

string Create(SubscriptionCreationOptions options,
string database = null);

string Create<T>(SubscriptionCreationOptions options = null,
string database = null);

string Create<T>(SubscriptionCreationOptions<T> options,
string database = null);

string Create<T>(Expression<Func<T, bool>> predicate,
PredicateSubscriptionCreationOptions options = null,
string database = null);

CreateAsync​

Create a subscription on the server asynchronously.

Task<string> CreateAsync(SubscriptionCreationOptions options,
string database = null,
CancellationToken token = default);

Task<string> CreateAsync<T>(SubscriptionCreationOptions options = null,
string database = null,
CancellationToken token = default);

Task<string> CreateAsync<T>(SubscriptionCreationOptions<T> options,
string database = null,
CancellationToken token = default);

Task<string> CreateAsync<T>(Expression<Func<T, bool>> predicate,
PredicateSubscriptionCreationOptions options = null,
string database = null,
CancellationToken token = default);

ParameterTypeDescription
predicateExpression<Func<T, bool>>A lambda expression returning a boolean that defines the subscription's filter.
optionsSubscriptionCreationOptions<T>, SubscriptionCreationOptions, or PredicateSubscriptionCreationOptionsThe subscription creation options. See the Classes below.
databasestringThe database where the subscription is created. If null, the document store's default database is used.
tokenCancellationTokenCreateAsync only.
A token used to cancel the creation operation.
Return value
string (Task<string> for CreateAsync)The name of the created subscription. If a name was provided in the options it is returned; otherwise the server generates a unique name.

Classes​

public sealed class SubscriptionCreationOptions<T>
{
public string Name { get; set; }
public Expression<Func<T, bool>> Filter { get; set; }
public Expression<Func<T, object>> Projection { get; set; }
public Action<ISubscriptionIncludeBuilder<T>> Includes { get; set; }
public string ChangeVector { get; set; }
public bool Disabled { get; set; }
public string MentorNode { get; set; }
public bool PinToMentorNode { get; set; }
public ArchivedDataProcessingBehavior? ArchivedDataProcessingBehavior { get; set; }
}
public sealed class PredicateSubscriptionCreationOptions
{
public string Name { get; set; }
public string ChangeVector { get; set; }
public bool Disabled { get; set; }
public string MentorNode { get; set; }
public bool PinToMentorNode { get; set; }
public ArchivedDataProcessingBehavior? ArchivedDataProcessingBehavior { get; set; }
}

PropertyTypeDescription
<T>TThe type whose collection the subscription draws its documents from.
NamestringA user-defined name for the subscription. Must be unique within the database.
QuerystringAn RQL query that defines the subscription.
See Subscription query.
FilterExpression<Func<T, bool>>A lambda expression defining the subscription's filter. Translated to a JavaScript function.
ProjectionExpression<Func<T, object>>A lambda expression defining the projection sent for each matching document. Translated to a JavaScript function.
The projection can create an anonymous object.
The projection can also create an object of a class or record you define, using an object initializer or a constructor call.
See Projecting into your own class or record.
IncludesAction<ISubscriptionIncludeBuilder<T>>An action defining the subscription's include clauses. Included documents, counters, and time series are part of the batch the subscription sends. The include methods can be chained.
ChangeVectorstringA change vector marking where the subscription starts processing. See Starting point.
Disabledbooltrue creates the subscription disabled, so the subscription does not accept worker connections until you enable it.
Default: false.
MentorNodestringThe 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.
PinToMentorNodebooltrue keeps the subscription on the node set in MentorNode, even while that node is down.
See Responsible node. Default: false.
ArchivedDataProcessingBehaviorArchivedDataProcessingBehavior?The subscription's handling of archived documents.
See Archived documents.

The SubscriptionUpdateOptions class adds two properties to the creation options:

PropertyTypeDescription
Idlong?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 the Name.
CreateNewboolWhat 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<T> object receives an ISubscriptionIncludeBuilder<T> 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.


Include builder: documents​

// Include the documents whose IDs are held by the field at the given path
ISubscriptionIncludeBuilder<T> IncludeDocuments(string path);
ISubscriptionIncludeBuilder<T> IncludeDocuments(Expression<Func<T, string>> path);
ISubscriptionIncludeBuilder<T> IncludeDocuments(Expression<Func<T, IEnumerable<string>>> path);

// The same, for a field holding IDs without their collection prefix
ISubscriptionIncludeBuilder<T> IncludeDocuments<TInclude>(Expression<Func<T, string>> path);
ISubscriptionIncludeBuilder<T> IncludeDocuments<TInclude>(Expression<Func<T, IEnumerable<string>>> path);

ParameterTypeDescription
pathstringThe path to the field holding the ID or IDs of the documents to include, e.g., "Employee" or "Lines[].Product".
pathExpression<Func<T, string>>An expression selecting the field holding the ID of the document to include, e.g., x => x.Employee.
pathExpression<Func<T, IEnumerable<string>>>An expression selecting the IDs of the documents to include, e.g., x => x.Lines.Select(y => y.Product).
<TInclude>TIncludeThe type of the included documents.
Use it when the field holds IDs without their collection prefix: the ID prefix of TInclude (e.g., products/) is added to each ID.

See Example: Including documents.


Include builder: counters​

// Include a single counter
ISubscriptionIncludeBuilder<T> IncludeCounter(string name);

// Include multiple counters
ISubscriptionIncludeBuilder<T> IncludeCounters(string[] names);

// Include ALL counters from ALL documents that match the subscription criteria
ISubscriptionIncludeBuilder<T> IncludeAllCounters();

ParameterTypeDescription
namestringThe name of a counter. The subscription includes every counter with this name in the documents it retrieves.
namesstring[]An array of counter names.

See Example: Including counters.


Include builder: time series​

// Include entries of a named time series, by a time range or by a number of entries
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string name, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string name, TimeSeriesRangeType type, int count);

// The same, for several named time series
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string[] names, TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeTimeSeries(string[] names, TimeSeriesRangeType type, int count);

// Include all time series
ISubscriptionIncludeBuilder<T> IncludeAllTimeSeries(TimeSeriesRangeType type, TimeValue time);
ISubscriptionIncludeBuilder<T> IncludeAllTimeSeries(TimeSeriesRangeType type, int count);

ParameterTypeDescription
name / namesstring / string[]The time series to include.
typeTimeSeriesRangeTypeThe range type, which must be Last.
timeTimeValueA time range to include, for example the last 7 days.
countintA number of entries to include, counted from the most recent.

See Example: Including time series.

In this article