---
source_url: https://www.pubnub.com/docs/sdks/java/api-reference/data-sync
title: DataSync API for Java SDK
updated_at: 2026-10-08T04:47:34.000Z
sdk_name: PubNub Java SDK
sdk_version: 14.0.0
---

# DataSync API for Java SDK

PubNub Java SDK, use the latest version: 14.0.0

Install:

```bash
Add PubNub dependency to your build@14.0.0
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

[DataSync](https://www.pubnub.com/docs/data-storage/structured-data/overview.md) is PubNub's data layer for storing application state (users, channels, memberships, and any custom object type) and keeping every connected client current through real-time events. Use it to model the objects your application works with and to react the moment they change.

DataSync is the successor to [App Context](https://www.pubnub.com/docs/sdks/java/api-reference/objects.md).

:::note DataSync entities and SDK entities are different things
This page is about **DataSync entities**, the records the service stores and treats as the source of truth for your application state. They are created and read through the `pubnub.dataSync().*` methods documented here.
An **SDK entity** is a local client-side handle such as `pubnub.channel("room-1")`. It carries no stored state of its own, it just gives you a scoped surface for subscribing and calling APIs. Refer to the [Channel SDK entity](https://www.pubnub.com/docs/sdks/java/entities/channel.md).
The two meet in the DataSync SDK entities ([DataSyncUser](https://www.pubnub.com/docs/sdks/java/entities/data-sync-user.md), [DataSyncChannel](https://www.pubnub.com/docs/sdks/java/entities/data-sync-channel.md), and [DataSyncEntity](https://www.pubnub.com/docs/sdks/java/entities/data-sync-entity.md)): SDK entities whose only job is to subscribe to a DataSync object's real-time updates.
:::

The classes that your objects conform to (their types and schemas) are defined through the Admin API or the [Admin Portal](https://admin.pubnub.com/), not through this SDK:

* Entity classes, which back users, channels, and custom entities: [list](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), [read](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-entity-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-entity-class-by-id.md). Partial updates aren't implemented; replace the complete class version instead.
* Relationship classes, which back memberships and custom relationships: [list](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), [read](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-relationship-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-relationship-class-by-name-and-version.md).

`User` and `Channel` entity classes and the `Membership` relationship class are predefined on every keyset, so you only need to define classes for your own custom entities and relationships.

A class definition is what decides, for every object of that class, which `payload` fields are filterable and sortable, which [projection](https://www.pubnub.com/docs/sdks/java/api-reference/access-manager.md#grant-token) each field belongs to, and how long the object lives before it expires. Refer to [managing classes](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#managing-classes) for more information.

A successful call yields a result object whose `getStatus()` returns the HTTP status. The `remove*` methods return the status on its own, every other method adds a `getData()` accessor holding the object, or the list of objects for a list method. A list method also adds a `getNext()` accessor holding the pagination state. The SDK does not surface the HATEOAS `links` the service sends. A stored object carries its free-form `status` and its `expiresAt` auto-deletion timestamp (ISO 8601) whenever those are set on it. A failed call surfaces as a `PubNubException` whose `getStatusCode()` is the HTTP status, for example `412`, and whose `getPubnubError()` is a `DATASYNC_*` category chosen from that status. Read the `DS-` error code with `DataSyncErrors.firstCode(exception)`, or every error item with `DataSyncErrors.from(exception)`. The raw response body stays in `getErrorMessage()` and `getJso()`. A response that carries no `DS-` code keeps the generic `HTTP_ERROR` category. You pass `payload` as a `Map<String, Object>`, and read it back as the same type from `getPayload()`.

### Authorization

Every DataSync request must be [authorized](https://www.pubnub.com/docs/data-storage/structured-data/access-control.md#authorizing-requests) with a token or signature. A request with no credential fails with a `401`; an invalid credential or a credential that doesn't permit the operation fails with a `403`.

A signature means the client is configured with a `secretKey`, and the SDK then signs every request with it automatically. Never put a secret key in a client-side application, use it only on a server you control. Give client-side applications a token from [grantToken()](https://www.pubnub.com/docs/sdks/java/api-reference/access-manager.md#grant-an-authorized-client-access-to-datasync-resources) instead, set with `setToken()`.

### Pagination

DataSync pagination is **forward-only**. There is no previous-page cursor, and `PNDataSyncPage` exposes no `getPrevCursor()` or `isHasPrev()`. To revisit an earlier page, page from the start again.

All list methods (`getUsers`, `getChannels`, `getMemberships`, `getEntities`, and `getRelationships`) accept `cursor` and `limit` (default `20`, max `100`) and return a result whose `getNext()` is a `PNDataSyncPage` with `isHasNext()`, `getCursor()`, and `getLimit()`. The `getNext()` accessor never returns `null`, it is an empty page when the server sends no pagination details, so read `isHasNext()` rather than checking `getNext()` for `null`.

To page forward, pass the returned `getNext().getCursor()` back as `cursor` on the next call, and stop when `getNext().isHasNext()` is `false`. `getCursor()` returns `null` on the last page. Refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination) for details.

### Filtering and sorting

All list methods accept two mutually exclusive filter parameters, `filterFast` and `filter`. The SDK sends whatever you set, so a call that carries both reaches the server and fails there with a `400`.

| Parameter | Consistency | Properties it can read | Expression complexity |
| --- | --- | --- | --- |
| `filterFast` | Strongly consistent, reflects the latest writes | Filtering mode `simple` or `full` | Up to 10 conditions by default (raisable per keyset) |
| `filter` | Eventually consistent, results can briefly lag writes | Filtering mode `full` only | Full expression language |

Reach for `filterFast` when the query has to see an object you just wrote, and for `filter` when you need the full expression language over a `full`-indexed property.

:::warning danger
filter
is not the strongly consistent one
The two names read the wrong way round if you assume `filter` is the basic option. `filterFast` is the strongly consistent, limited one. `filter` is the richer, eventually consistent one.
:::

Both parameters share the same expression language, a string built from a property name, an operator, and a value:

| Operators |  |
| --- | --- |
| Comparison | `==`, `!=`, `<`, `>`, `<=`, `>=` |
| Pattern matching | `LIKE` (case-insensitive), `SLIKE` (case-sensitive), `ILIKE` (case-insensitive, same as `LIKE`) |
| Logical | `&&`, `||`, `!`, and parentheses for grouping |

Values are quoted strings, numbers, `true`, `false`, or `null`. Pattern operators (`LIKE`, `SLIKE`, `ILIKE`) apply to string properties only, and `null` is only valid with `==` and `!=`. Reference a property by its `name`, not its declared `path`, and only properties declared on the class are filterable. To reach a nested `payload` property, declare it as a class property first, then filter by that property's `name`, for example `"price < 100"` for a `product` class that declares `price`.

Some examples:

```java
.filterFast("price < 100")                                // strongly consistent, single condition
.filterFast("(price < 100 && stock > 0) || price > 500")  // strongly consistent, grouped conditions
.filter("name LIKE \"*sneaker*\"")                        // eventually consistent, needs filtering mode "full"
.filter("!(status == \"discontinued\")")                  // eventually consistent, negated condition
```

Both parameters only work over properties declared on the class, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, which are always filterable and sortable without being declared. `eTag` and `expiresAt` are neither. The `status` exception does not hold if the class redeclares `/status` scoped to projections your token cannot fully reach. When you don't pass `classVersion`, the list includes items of every version, but `filter`, `filterFast`, and `sort` can only use properties declared on the latest version of the class. A property that exists only in an older version is rejected with a `400`. Pass `classVersion` to use properties declared on an older version. Refer to [filtering](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#filtering) for the two filtering tiers, and [property definitions](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#property-definitions) for how properties are declared.

Use `sort` to order results. Pass a `List<PNDataSyncSortField>` in priority order, where each `PNDataSyncSortField` names a `property` and sets `ascending` (default `true`). The SDK joins the list into a comma-separated request value and appends `:desc` to each descending field. A bare name sorts ascending:

```java
.sort(Arrays.asList(new PNDataSyncSortField("price", false)))                                    // single field, descending
.sort(Arrays.asList(new PNDataSyncSortField("type"), new PNDataSyncSortField("price", false)))  // type ascending, then price descending
.sort(Arrays.asList(new PNDataSyncSortField("createdAt", true)))                                 // explicit ascending
```

The `+field` and `-field` prefixes are **not** accepted. A leading `-` is read as part of the property name, so `new PNDataSyncSortField("-price")` fails with a `400`. Only properties declared on the class with a filtering mode other than `none` can be sorted on when sorting alone or alongside `filterFast`. Sorting alongside `filter` additionally requires the field to be declared `full`. The built-in fields `id`, `createdAt`, `updatedAt`, and `status` are always sortable without declaring them on the class.

The SDK doesn't validate `filterFast`, `filter`, `sort`, or `limit` locally, it passes them through as-is. An invalid expression, an unsortable field, or an out-of-range `limit` only surfaces as an error response from the server, not as a client-side exception. The only local checks are a blank `sort` property on any list method, a blank `className` (on `createEntity`, `getEntities`, `createRelationship`, and `getRelationships`, or on `createUser`, `getUsers`, `createChannel`, and `getChannels` when you pass one), and a blank resource id. These fail with a `PubNubException` before anything is sent. The exception is thrown by `sync()` and delivered to the failure callback by `async()`.

### Concurrency (ETag)

Every stored object carries an `eTag`. To guard against concurrent writes, pass the `eTag` you read earlier as `ifMatch` on `set*`, `update*`, and `remove*` calls. The SDK sends it as the `If-Match` request header.

If the server-side value has changed in the meantime, the operation fails with a `412`, and you should re-read the object and retry. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for details.

### Partial updates

The `update*` methods apply a partial update using raw JSON Patch (RFC 6902). Pass a `List<PNJsonPatchOperation>`. Each `PNJsonPatchOperation` has an `op` (`add`, `remove`, `replace`, `move`, `copy`, or `test`, written as a string), a `path` (a full JSON Pointer, for example `/status` or `/payload/price`), and, depending on the operation, a `value` or a `from`. Build one with `PNJsonPatchOperation.builder()`.

Each path is a full JSON Pointer (RFC 6901) and is sent as you write it. The SDK does **not** add a `/payload` prefix. To target a field inside `payload`, include the prefix yourself, for example `/payload/price`, not `/price`. A bare `/price` targets a top-level field named `price`, which doesn't exist. Top-level fields like `/status` can be patched directly. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for details.

Correct patch forms:

```java
PNJsonPatchOperation.builder().op("add").path("/payload/tags").value("sale").build()           // adds a value inside payload.tags
PNJsonPatchOperation.builder().op("replace").path("/payload/price").value(79.99).build()       // replaces payload.price
PNJsonPatchOperation.builder().op("remove").path("/payload/tempFlag").build()                  // removes payload.tempFlag
PNJsonPatchOperation.builder().op("move").from("/payload/oldTag").path("/payload/tag").build()
PNJsonPatchOperation.builder().op("copy").from("/payload/price").path("/payload/msrp").build()
PNJsonPatchOperation.builder().op("test").path("/status").value("active").build()              // fails the patch if the current value doesn't match
```

`move` and `copy` require `from` (the source pointer) instead of `value`. `test` requires `value` and fails the entire patch if the current value at `path` doesn't match, use it to guard the rest of the operations against a stale read.

Paths address the object's stored property names, the same keys that come back in responses. The class version is `entityClassVersion` on users, channels, and entities, and `relationshipClassVersion` on memberships and relationships. The fields set at creation cannot be patched: `entityClass` and `entityClassLevel` on users, channels, and entities, `relationshipClass`, `entityAId`, and `entityBId` on relationships, and `userId` and `channelId` on memberships.

All operations in the call apply together or not at all.

The `operations` list must contain at least one operation. The SDK checks this before it sends anything and fails the call with a `PubNubException` carrying `JSON_PATCH_OPERATIONS_MISSING` if the list is empty. The exception is thrown by `sync()` and delivered to the failure callback by `async()`.

### Expiry (TTL)

An object's `expiresAt` is computed once when the object is created, and updates never refresh it. The value is the creation time plus the class TTL, rounded up to the start of the next whole UTC day, so it rarely lands exactly one TTL from the moment you wrote the object.

Entity classes you create default to a 31-day TTL, while the built-in Global `User` and `Channel` classes use 30 days. TTL cannot be disabled. A relationship expires at the earlier expiry time of the two entities it links, fixed when the relationship is created.

Refer to [data expiry](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#data-expiry-ttl) for details.

:::note Request execution
Every DataSync method returns an endpoint object, and nothing is sent until you call `sync()` or `async()` on it. Required parameters go in the method call, and optional ones are set by chaining setters on the returned endpoint object.
`sync()` blocks and returns the result, or throws a `PubNubException`. `async()` takes a callback that receives a `Result`, so you handle success and failure inside the callback. Use `async()` on any thread you cannot block.
:::

:::note Requires Access Manager
DataSync requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

## Users

Users are built-in objects. There are no top-level `name` or `email` fields, all application data lives in the free-form `payload`. Refer to [users](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#users) for the concept.

A user is an entity of the built-in `User` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. To give your users their own declared, filterable properties, define a subclass of `User` with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) and pass its name as `className`.

### Create user

Creates a user. Supply a `userId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```java
pubnub.dataSync().createUser(int classVersion)
    .userId(String)
    .className(String)
    .classLevel(PNDataSyncClassLevel)
    .status(String)
    .payload(Map<String, Object>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| classVersion | int | Yes |  | Version of the user class schema. |
| userId | String | Optional | `server-generated` | User identifier. Omit to let the server generate a UUID. Max 255 characters. |
| className | String | Optional | `User` | Name of the entity class this user belongs to. Must be `User` or one of its subclasses. Defaults to `User` on the server if omitted. Set at creation and immutable afterward. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Alice");
payload.put("type", "shopper");

pubnub.dataSync().createUser(1)
        .userId("user-alice")
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Created user " + value.getData().getId() + " with eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get user

Returns a single user by `userId`.

#### Method(s)

```java
pubnub.dataSync().getUser(String userId)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getUser("user-alice")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Fetched user " + value.getData().getId() + " with payload " + value.getData().getPayload());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get all users

Returns a paginated list of users. All parameters are optional, so you can call `getUsers()` without setting any of them. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```java
pubnub.dataSync().getUsers()
    .className(String)
    .classVersion(Integer)
    .classLevel(PNDataSyncClassLevel)
    .filterFast(String)
    .filter(String)
    .sort(List<PNDataSyncSortField>)
    .limit(Integer)
    .cursor(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Optional | `all user classes` | User class to list. Omit to list the Global `User` class and all of its subclasses. |
| classVersion | Integer | Optional | `all versions` | User class version to list. Omit to list users across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional |  | Order results. Each entry names a property and a direction, for example `new PNDataSyncSortField("createdAt", false)`. |
| limit | Integer | Optional | `20` | Maximum number of users per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getUsers()
        .limit(10)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "user-alice",
            "entityClass": "User",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Alice", "type": "shopper" },
            "createdAt": "2026-07-13T09:00:00.000Z",
            "updatedAt": "2026-07-13T09:00:00.000Z",
            "eTag": "AbCdEfGhIjKlMn"
        }
    ],
    "meta": {
        "next_cursor": "b2Zmc2V0PTIw",
        "has_next": true,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call. The built-in `User` class declares only `name` and `type`, so those, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, are what you can filter on. To filter on other payload fields, such as `email`, define a subclass of `User` that declares them and pass it as `className`.

```java
pubnub.dataSync().getUsers()
        .filterFast("type == \"shopper\"")
        .sort(Collections.singletonList(new PNDataSyncSortField("name")))
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```java
pubnub.dataSync().getUsers()
        .filter("name LIKE \"Alice*\"")
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getNext().getCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getNext().isHasNext()` is `false`.

```java
private void fetchUsersPage(PubNub pubnub, String cursor) {
    pubnub.dataSync().getUsers()
            .limit(20)
            .cursor(cursor)
            .async(result -> {
                result.onSuccess(value -> {
                    value.getData().forEach(item -> System.out.println(item.getId()));
                    if (value.getNext().isHasNext()) {
                        fetchUsersPage(pubnub, value.getNext().getCursor());
                    }
                }).onFailure(exception -> {
                    System.out.println("Failed: " + exception.getMessage());
                });
            });
}
// Start with the first page by passing a null cursor: fetchUsersPage(pubnub, null)
```

### Set user

Replaces a user in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update user](#update-user).

#### Method(s)

```java
pubnub.dataSync().setUser(String userId, int classVersion)
    .status(String)
    .payload(Map<String, Object>)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| classVersion | int | Yes |  | Version of the user class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Alice B.");
payload.put("type", "shopper");

pubnub.dataSync().setUser("user-alice", 1)
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Replaced user " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:15:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Update user

Applies a partial update to a user with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```java
pubnub.dataSync().updateUser(String userId, List<PNJsonPatchOperation> operations)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().updateUser("user-alice", Collections.singletonList(
        PNJsonPatchOperation.builder().op("replace").path("/payload/name").value("Alice B.").build()))
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Updated user " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "status": "active",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:20:00.000Z",
        "eTag": "EfGhIjKlMnOpQr"
    }
}
```

### Remove user

Deletes a user by `userId`.

#### Method(s)

```java
pubnub.dataSync().removeUser(String userId)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes |  | User identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().removeUser("user-alice")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Removed user, HTTP status " + value.getStatus());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200
}
```

## Channels

Channels work like users. They have no top-level `name` field, all application data lives in `payload`, and they support the same operations. Refer to [channels](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#channels) for the concept.

A channel is an entity of the built-in `Channel` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. Subclass it with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to add declared properties, then pass the subclass name as `className`.

### Create channel

Creates a channel. Supply a `channelId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```java
pubnub.dataSync().createChannel(int classVersion)
    .channelId(String)
    .className(String)
    .classLevel(PNDataSyncClassLevel)
    .status(String)
    .payload(Map<String, Object>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| classVersion | int | Yes |  | Version of the channel class schema. |
| channelId | String | Optional | `server-generated` | Channel identifier. Omit to let the server generate a UUID. Max 255 characters. |
| className | String | Optional | `Channel` | Name of the entity class this channel belongs to. Must be `Channel` or one of its subclasses. Defaults to `Channel` on the server if omitted. Set at creation and immutable afterward. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Summer Sale");
payload.put("type", "promotion");

pubnub.dataSync().createChannel(1)
        .channelId("channel-summer-sale")
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Created channel " + value.getData().getId() + " with eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get channel

Returns a single channel by `channelId`.

#### Method(s)

```java
pubnub.dataSync().getChannel(String channelId)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getChannel("channel-summer-sale")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Fetched channel " + value.getData().getId() + " with payload " + value.getData().getPayload());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get all channels

Returns a paginated list of channels. All parameters are optional, so you can call `getChannels()` without setting any of them. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```java
pubnub.dataSync().getChannels()
    .className(String)
    .classVersion(Integer)
    .classLevel(PNDataSyncClassLevel)
    .filterFast(String)
    .filter(String)
    .sort(List<PNDataSyncSortField>)
    .limit(Integer)
    .cursor(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Optional | `all channel classes` | Channel class to list. Omit to list the Global `Channel` class and all of its subclasses. |
| classVersion | Integer | Optional | `all versions` | Channel class version to list. Omit to list channels across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional |  | Order results. Each entry names a property and a direction. |
| limit | Integer | Optional | `20` | Maximum number of channels per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getChannels()
        .limit(10)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "channel-summer-sale",
            "entityClass": "Channel",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Summer Sale", "type": "promotion" },
            "createdAt": "2026-07-13T09:05:00.000Z",
            "updatedAt": "2026-07-13T09:05:00.000Z",
            "eTag": "GhIjKlMnOpQrSt"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call. The built-in `Channel` class declares only `name` and `type`, so those, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, are what you can filter on. To filter on other payload fields, such as `region`, define a subclass of `Channel` that declares them and pass it as `className`.

```java
pubnub.dataSync().getChannels()
        .filterFast("type == \"promotion\"")
        .sort(Collections.singletonList(new PNDataSyncSortField("name")))
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```java
pubnub.dataSync().getChannels()
        .filter("name LIKE \"Summer*\"")
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getNext().getCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getNext().isHasNext()` is `false`.

```java
private void fetchChannelsPage(PubNub pubnub, String cursor) {
    pubnub.dataSync().getChannels()
            .limit(20)
            .cursor(cursor)
            .async(result -> {
                result.onSuccess(value -> {
                    value.getData().forEach(item -> System.out.println(item.getId()));
                    if (value.getNext().isHasNext()) {
                        fetchChannelsPage(pubnub, value.getNext().getCursor());
                    }
                }).onFailure(exception -> {
                    System.out.println("Failed: " + exception.getMessage());
                });
            });
}
// Start with the first page by passing a null cursor: fetchChannelsPage(pubnub, null)
```

### Set channel

Replaces a channel in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update channel](#update-channel).

#### Method(s)

```java
pubnub.dataSync().setChannel(String channelId, int classVersion)
    .status(String)
    .payload(Map<String, Object>)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| classVersion | int | Yes |  | Version of the channel class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Summer Sale 2026");
payload.put("type", "promotion");

pubnub.dataSync().setChannel("channel-summer-sale", 1)
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Replaced channel " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:00:00.000Z",
        "eTag": "IjKlMnOpQrStUv"
    }
}
```

### Update channel

Applies a partial update to a channel with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```java
pubnub.dataSync().updateChannel(String channelId, List<PNJsonPatchOperation> operations)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().updateChannel("channel-summer-sale", Collections.singletonList(
        PNJsonPatchOperation.builder().op("replace").path("/payload/name").value("Summer Sale 2026").build()))
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Updated channel " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "status": "active",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:05:00.000Z",
        "eTag": "KlMnOpQrStUvWx"
    }
}
```

### Remove channel

Deletes a channel by `channelId`.

#### Method(s)

```java
pubnub.dataSync().removeChannel(String channelId)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Channel identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().removeChannel("channel-summer-sale")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Removed channel, HTTP status " + value.getStatus());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200
}
```

## Memberships

A membership links a user to a channel and carries its own `payload`. In the running example, Alice is a member of `channel-summer-sale` with the payload `{ "role": "viewer" }`. Refer to [memberships](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#memberships) for the concept.

A membership is a relationship of the built-in Global `Membership` [relationship class](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), whose two sides are surfaced as `channelId` and `userId`. Every membership response includes both `relationshipClass` and `relationshipClassVersion`. The class is assigned by the service, so the `createMembership` and `setMembership` methods take no class parameter.

Relationship classes [don't support inheritance](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#relationship-class-inheritance), and only the Global `Membership` class produces memberships, so `relationshipClass` is always `Membership` and `relationshipClassVersion` is the only part that varies.

### Create membership

Creates a membership linking a user to a channel. The `userId`/`channelId` pair must be unique for the membership class. A membership that duplicates an existing pair is rejected with a `409`.

#### Method(s)

```java
pubnub.dataSync().createMembership(String channelId, String userId, int classVersion)
    .membershipId(String)
    .status(String)
    .payload(Map<String, Object>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes |  | Identifier of the channel in the membership. |
| userId | String | Yes |  | Identifier of the user in the membership. |
| classVersion | int | Yes |  | Version of the Membership relationship class schema. |
| membershipId | String | Optional | `server-generated` | Membership identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("role", "viewer");

pubnub.dataSync().createMembership("channel-summer-sale", "user-alice", 1)
        .membershipId("membership-alice-summer-sale")
        .status("active")
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Created membership " + value.getData().getId() + " with eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get membership

Returns a single membership by `membershipId`.

#### Method(s)

```java
pubnub.dataSync().getMembership(String membershipId)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getMembership("membership-alice-summer-sale")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Fetched membership " + value.getData().getId() + " with payload " + value.getData().getPayload());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get all memberships

Returns a paginated list of memberships. All parameters are optional, so you can call `getMemberships()` without setting any of them. `userId` and `channelId` can be set independently, together, or omitted entirely. Filter by `userId` to list a user's memberships or by `channelId` to list a channel's members. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```java
pubnub.dataSync().getMemberships()
    .channelId(String)
    .userId(String)
    .classVersion(Integer)
    .filterFast(String)
    .filter(String)
    .sort(List<PNDataSyncSortField>)
    .limit(Integer)
    .cursor(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Optional |  | List only memberships for this channel. |
| userId | String | Optional |  | List only memberships for this user. |
| classVersion | Integer | Optional | `all versions` | Membership class version to list. Omit to list memberships across every version of the class. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional |  | Order results. Each entry names a property and a direction. |
| limit | Integer | Optional | `20` | Maximum number of memberships per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getMemberships()
        .userId("user-alice")
        .limit(10)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "membership-alice-summer-sale",
            "channelId": "channel-summer-sale",
            "userId": "user-alice",
            "relationshipClass": "Membership",
            "relationshipClassVersion": 1,
            "payload": { "role": "viewer" },
            "createdAt": "2026-07-13T09:10:00.000Z",
            "updatedAt": "2026-07-13T09:10:00.000Z",
            "eTag": "MnOpQrStUvWxYz"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List a channel's members with channelId

Pass `channelId` instead of `userId` to list the members of a channel rather than a user's memberships.

```java
pubnub.dataSync().getMemberships()
        .channelId("channel-summer-sale")
        .limit(50)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getUserId() + " is a member of " + item.getChannelId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```java
// Membership payload fields such as `role` are not filterable, filter on `status` instead
pubnub.dataSync().getMemberships()
        .userId("user-alice")
        .filterFast("status == \"active\"")
        .sort(Collections.singletonList(new PNDataSyncSortField("createdAt", false)))
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```java
// Membership payload fields such as `role` are not filterable, filter on `status` instead
pubnub.dataSync().getMemberships()
        .userId("user-alice")
        .filter("status LIKE \"act*\"")
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getNext().getCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getNext().isHasNext()` is `false`.

```java
private void fetchMembershipsPage(PubNub pubnub, String cursor) {
    pubnub.dataSync().getMemberships()
            .userId("user-alice")
            .limit(20)
            .cursor(cursor)
            .async(result -> {
                result.onSuccess(value -> {
                    value.getData().forEach(item -> System.out.println(item.getId()));
                    if (value.getNext().isHasNext()) {
                        fetchMembershipsPage(pubnub, value.getNext().getCursor());
                    }
                }).onFailure(exception -> {
                    System.out.println("Failed: " + exception.getMessage());
                });
            });
}
// Start with the first page by passing a null cursor: fetchMembershipsPage(pubnub, null)
```

### Set membership

Replaces a membership in full (PUT). Send the complete set of fields, any field you omit is cleared. The linked user and channel are immutable, so `setMembership` doesn't expose `channelId`/`userId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update membership](#update-membership).

#### Method(s)

```java
pubnub.dataSync().setMembership(String membershipId, int classVersion)
    .status(String)
    .payload(Map<String, Object>)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| classVersion | int | Yes |  | Version of the Membership relationship class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("role", "moderator");

pubnub.dataSync().setMembership("membership-alice-summer-sale", 1)
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Replaced membership " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:00:00.000Z",
        "eTag": "OpQrStUvWxYzAb"
    }
}
```

### Update membership

Applies a partial update to a membership with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```java
pubnub.dataSync().updateMembership(String membershipId, List<PNJsonPatchOperation> operations)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().updateMembership("membership-alice-summer-sale", Collections.singletonList(
        PNJsonPatchOperation.builder().op("replace").path("/payload/role").value("moderator").build()))
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Updated membership " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "status": "active",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:05:00.000Z",
        "eTag": "QrStUvWxYzAbCd"
    }
}
```

### Remove membership

Deletes a membership by `membershipId`.

#### Method(s)

```java
pubnub.dataSync().removeMembership(String membershipId)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | String | Yes |  | Membership identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().removeMembership("membership-alice-summer-sale")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Removed membership, HTTP status " + value.getStatus());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200
}
```

## Entities

Entities are instances of the custom [entity classes](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md) you define on your keyset. In the running example, `product` is a class and `product-sneaker-42` is an instance. Use [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to declare a class, and [Get entity class by ID](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md) to read the property, filtering, and projection declarations that govern its instances.

Entity classes can extend one another. Listing a class also returns the entities of its subclasses, so `getEntities("product")` returns every `product` plus every instance of a class that extends `product`.

### Create entity

Creates an entity of a given class and version.

#### Method(s)

```java
pubnub.dataSync().createEntity(String className, int classVersion)
    .entityId(String)
    .classLevel(PNDataSyncClassLevel)
    .status(String)
    .payload(Map<String, Object>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the entity class this instance belongs to. Set at creation and immutable afterward. |
| classVersion | int | Yes |  | Version of the entity class schema. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| entityId | String | Optional | `server-generated` | Entity identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Retro Sneaker");
payload.put("price", 89.99);
payload.put("stock", 12);

pubnub.dataSync().createEntity("product", 1)
        .entityId("product-sneaker-42")
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Created entity " + value.getData().getId() + " with eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get entity

Returns a single entity by `entityId`.

#### Method(s)

```java
pubnub.dataSync().getEntity(String entityId)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getEntity("product-sneaker-42")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Fetched entity " + value.getData().getId() + " with payload " + value.getData().getPayload());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get all entities

Returns a paginated list of entities within a class. The `className` parameter is required, entities are always listed within the context of their class. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```java
pubnub.dataSync().getEntities(String className)
    .classVersion(Integer)
    .classLevel(PNDataSyncClassLevel)
    .filterFast(String)
    .filter(String)
    .sort(List<PNDataSyncSortField>)
    .limit(Integer)
    .cursor(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the entity class to list. |
| classVersion | Integer | Optional | `all versions` | Entity class version to list. Omit to list entities across every version of the class. |
| classLevel | PNDataSyncClassLevel | Optional | `service default` | Class hierarchy level of `className`, either `GLOBAL` for a class the service provides or `SUBKEY` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional |  | Order results. Each entry names a property and a direction. |
| limit | Integer | Optional | `20` | Maximum number of entities per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getEntities("product")
        .limit(10)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "product-sneaker-42",
            "entityClass": "product",
            "entityClassVersion": 1,
            "entityClassLevel": "SubKey",
            "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
            "createdAt": "2026-07-13T09:15:00.000Z",
            "updatedAt": "2026-07-13T09:15:00.000Z",
            "eTag": "StUvWxYzAbCdEf"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```java
// `price` and `stock` must be declared filterable (`simple` or `full`) on the `product` class
pubnub.dataSync().getEntities("product")
        .filterFast("price < 100 && stock > 0")
        .sort(Collections.singletonList(new PNDataSyncSortField("price")))
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```java
// `filter` only accepts properties declared with `full` filtering on the `product` class
pubnub.dataSync().getEntities("product")
        .filter("name LIKE \"*Sneaker*\"")
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getNext().getCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getNext().isHasNext()` is `false`.

```java
private void fetchEntitiesPage(PubNub pubnub, String cursor) {
    pubnub.dataSync().getEntities("product")
            .limit(20)
            .cursor(cursor)
            .async(result -> {
                result.onSuccess(value -> {
                    value.getData().forEach(item -> System.out.println(item.getId()));
                    if (value.getNext().isHasNext()) {
                        fetchEntitiesPage(pubnub, value.getNext().getCursor());
                    }
                }).onFailure(exception -> {
                    System.out.println("Failed: " + exception.getMessage());
                });
            });
}
// Start with the first page by passing a null cursor: fetchEntitiesPage(pubnub, null)
```

### Set entity

Replaces an entity in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update entity](#update-entity).

#### Method(s)

```java
pubnub.dataSync().setEntity(String entityId, int classVersion)
    .status(String)
    .payload(Map<String, Object>)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| classVersion | int | Yes |  | Version of the entity class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("name", "Retro Sneaker");
payload.put("price", 79.99);
payload.put("stock", 8);

pubnub.dataSync().setEntity("product-sneaker-42", 1)
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Replaced entity " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:00:00.000Z",
        "eTag": "UvWxYzAbCdEfGh"
    }
}
```

### Update entity

Applies a partial update to an entity with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```java
pubnub.dataSync().updateEntity(String entityId, List<PNJsonPatchOperation> operations)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().updateEntity("product-sneaker-42", Arrays.asList(
        PNJsonPatchOperation.builder().op("replace").path("/payload/price").value(79.99).build(),
        PNJsonPatchOperation.builder().op("replace").path("/payload/stock").value(8).build()))
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Updated entity " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 8 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:05:00.000Z",
        "eTag": "WxYzAbCdEfGhIj"
    }
}
```

#### Other examples

##### Combine patch operations, and guard the write with ifMatch

A single `updateEntity` call can mix `add`, `replace`, `remove`, `move`, `copy`, and `test` operations in one `operations` list. All operations in the call apply together or not at all. Add `ifMatch` (the `eTag` from a prior read) to reject the patch with a `412` if the entity changed since you read it, instead of silently overwriting a concurrent change.

```java
List<PNJsonPatchOperation> operations = Arrays.asList(
        // Fail the whole patch unless the name is still "Retro Sneaker"
        PNJsonPatchOperation.builder().op("test").path("/payload/name").value("Retro Sneaker").build(),
        // Keep the old price before changing it
        PNJsonPatchOperation.builder().op("copy").path("/payload/previousPrice").from("/payload/price").build(),
        PNJsonPatchOperation.builder().op("replace").path("/payload/price").value(79.99).build(),
        PNJsonPatchOperation.builder().op("replace").path("/payload/stock").value(8).build(),
        PNJsonPatchOperation.builder().op("add").path("/payload/sale").value(true).build(),
        // Rename a field
        PNJsonPatchOperation.builder().op("move").path("/payload/onSale").from("/payload/sale").build(),
        // The removed field must exist on the entity, otherwise the patch is rejected
        PNJsonPatchOperation.builder().op("remove").path("/payload/legacySku").build());

pubnub.dataSync().updateEntity("product-sneaker-42", operations)
        // Use the eTag from an earlier read of the entity, not a literal value
        .ifMatch("a1b2c3d4e5f6")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Patched " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

### Remove entity

Deletes an entity by `entityId`.

#### Method(s)

```java
pubnub.dataSync().removeEntity(String entityId)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | String | Yes |  | Entity identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().removeEntity("product-sneaker-42")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Removed entity, HTTP status " + value.getStatus());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200
}
```

## Relationships

A relationship links two entities and carries its own `payload`. In the running example, the `ProductOwner` relationship links `seller-bob` to `product-sneaker-42`.

Relationships are instances of the [relationship classes](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md) you define on your keyset. A relationship class declares the cardinality the service enforces (`one-to-one`, `one-to-many`, or `many-to-many`) and, optionally, which entity class each side must belong to. Use [Create a new relationship class](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md) to declare a class, and [Get relationship class by name and version](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md) to read it back.

### Create relationship

Creates a relationship between two entities. The relationship class's cardinality (one-to-one, one-to-many, or many-to-many) is enforced on create. A relationship that violates its class's cardinality is rejected with a `409`.

#### Method(s)

```java
pubnub.dataSync().createRelationship(String entityAId, String entityBId, String className, int classVersion)
    .relationshipId(String)
    .status(String)
    .payload(Map<String, Object>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityAId | String | Yes |  | Identifier of the first linked entity. Immutable after creation. |
| entityBId | String | Yes |  | Identifier of the second linked entity. Immutable after creation. |
| className | String | Yes |  | Name of the relationship class this instance belongs to. Set at creation and immutable afterward. |
| classVersion | int | Yes |  | Version of the relationship class schema. |
| relationshipId | String | Optional | `server-generated` | Relationship identifier. Omit to let the server generate a UUID. Max 255 characters. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("since", "2026-07-13");

pubnub.dataSync().createRelationship("seller-bob", "product-sneaker-42", "ProductOwner", 1)
        .relationshipId("rel-bob-owns-sneaker-42")
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Created relationship " + value.getData().getId() + " with eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get relationship

Returns a single relationship by `relationshipId`.

#### Method(s)

```java
pubnub.dataSync().getRelationship(String relationshipId)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getRelationship("rel-bob-owns-sneaker-42")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Fetched relationship " + value.getData().getId() + " with payload " + value.getData().getPayload());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get all relationships

Returns a paginated list of relationships within a class. The `className` parameter is required. Filter by `entityAId` or `entityBId` to list a specific entity's links. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```java
pubnub.dataSync().getRelationships(String className)
    .entityAId(String)
    .entityBId(String)
    .classVersion(Integer)
    .filterFast(String)
    .filter(String)
    .sort(List<PNDataSyncSortField>)
    .limit(Integer)
    .cursor(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| className | String | Yes |  | Name of the relationship class to list. |
| entityAId | String | Optional |  | List only relationships whose first entity is this id. |
| entityBId | String | Optional |  | List only relationships whose second entity is this id. |
| classVersion | Integer | Optional | `all versions` | Relationship class version to list. Omit to list relationships across every version of the class. |
| filterFast | String | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | String | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | List<PNDataSyncSortField> | Optional |  | Order results. Each entry names a property and a direction. |
| limit | Integer | Optional | `20` | Maximum number of relationships per page. Max `100`. |
| cursor | String | Optional |  | Opaque pagination cursor. Omit for the first page. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().getRelationships("ProductOwner")
        .limit(10)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "rel-bob-owns-sneaker-42",
            "entityAId": "seller-bob",
            "entityBId": "product-sneaker-42",
            "relationshipClass": "ProductOwner",
            "relationshipClassVersion": 1,
            "payload": { "since": "2026-07-13" },
            "createdAt": "2026-07-13T09:20:00.000Z",
            "updatedAt": "2026-07-13T09:20:00.000Z",
            "eTag": "YzAbCdEfGhIjKl"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List an entity's incoming links with entityBId

Pass `entityBId` instead of `entityAId` to list relationships where the entity is on the second side of the link.

```java
pubnub.dataSync().getRelationships("ProductOwner")
        .entityBId("product-sneaker-42")
        .limit(50)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getEntityAId() + " owns " + item.getEntityBId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```java
// `tier` and `since` must be declared filterable (`simple` or `full`) on the `ProductOwner` class
pubnub.dataSync().getRelationships("ProductOwner")
        .filterFast("tier == \"gold\"")
        .sort(Collections.singletonList(new PNDataSyncSortField("since", false)))
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```java
// `filter` only accepts properties declared with `full` filtering on the `ProductOwner` class
pubnub.dataSync().getRelationships("ProductOwner")
        .filter("tier LIKE \"gold*\"")
        .limit(20)
        .async(result -> {
            result.onSuccess(value -> {
                value.getData().forEach(item -> System.out.println(item.getId()));
                System.out.println("More pages available: " + value.getNext().isHasNext());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getNext().getCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getNext().isHasNext()` is `false`.

```java
private void fetchRelationshipsPage(PubNub pubnub, String cursor) {
    pubnub.dataSync().getRelationships("ProductOwner")
            .limit(20)
            .cursor(cursor)
            .async(result -> {
                result.onSuccess(value -> {
                    value.getData().forEach(item -> System.out.println(item.getId()));
                    if (value.getNext().isHasNext()) {
                        fetchRelationshipsPage(pubnub, value.getNext().getCursor());
                    }
                }).onFailure(exception -> {
                    System.out.println("Failed: " + exception.getMessage());
                });
            });
}
// Start with the first page by passing a null cursor: fetchRelationshipsPage(pubnub, null)
```

### Set relationship

Replaces a relationship in full (PUT). Send the complete set of fields, any field you omit is cleared. `className` is immutable after creation and cannot be sent, and the linked entity ids are immutable too, so `setRelationship` doesn't expose `entityAId`/`entityBId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatch`. For a partial update, use [Update relationship](#update-relationship).

#### Method(s)

```java
pubnub.dataSync().setRelationship(String relationshipId, int classVersion)
    .status(String)
    .payload(Map<String, Object>)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| classVersion | int | Yes |  | Version of the relationship class schema. |
| status | String | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | Map<String, Object> | Optional |  | Free-form JSON object holding your application data. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
Map<String, Object> payload = new HashMap<>();
payload.put("since", "2026-07-13");
payload.put("tier", "gold");

pubnub.dataSync().setRelationship("rel-bob-owns-sneaker-42", 1)
        .payload(payload)
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Replaced relationship " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "gold" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Update relationship

Applies a partial update to a relationship with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```java
pubnub.dataSync().updateRelationship(String relationshipId, List<PNJsonPatchOperation> operations)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| operations | List<PNJsonPatchOperation> | Yes |  | One or more JSON Patch operations. Must contain at least one item. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().updateRelationship("rel-bob-owns-sneaker-42", Collections.singletonList(
        PNJsonPatchOperation.builder().op("replace").path("/payload/tier").value("platinum").build()))
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Updated relationship " + value.getData().getId() + ", new eTag " + value.getData().getETag());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "platinum" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:05:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Remove relationship

Deletes a relationship by `relationshipId`.

#### Method(s)

```java
pubnub.dataSync().removeRelationship(String relationshipId)
    .ifMatch(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | String | Yes |  | Relationship identifier. |
| ifMatch | String | Optional |  | The `eTag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```java
pubnub.dataSync().removeRelationship("rel-bob-owns-sneaker-42")
        .async(result -> {
            result.onSuccess(value -> {
                System.out.println("Removed relationship, HTTP status " + value.getStatus());
            }).onFailure(exception -> {
                System.out.println("Failed: " + exception.getMessage());
            });
        });
```

#### Response

```json
{
    "status": 200
}
```

## Real-time updates

DataSync objects can publish `create`, `update`, and `delete` events that you receive in real time with a DataSync listener on a `Subscription`, a `SubscriptionSet`, or the PubNub client. Create a DataSync SDK entity for the object ([DataSyncUser](https://www.pubnub.com/docs/sdks/java/entities/data-sync-user.md), [DataSyncChannel](https://www.pubnub.com/docs/sdks/java/entities/data-sync-channel.md), or [DataSyncEntity](https://www.pubnub.com/docs/sdks/java/entities/data-sync-entity.md)), subscribe to it, and attach the listener, as described in [Add DataSync listener](https://www.pubnub.com/docs/sdks/java/api-reference/publish-and-subscribe.md#add-datasync-listener).

```java
Subscription subscription = pubnub.channel("product-sneaker-42").subscription();

subscription.addListener(new EventListener() {
    @Override
    public void dataSync(@NotNull PubNub pubnub, @NotNull PNDataSyncEventResult result) {
        PNDataSyncEventMessage message = result.getExtractedMessage();
        if (message instanceof PNSetDataSyncUserEventMessage) {
            PNSetDataSyncUserEventMessage set = (PNSetDataSyncUserEventMessage) message;
            System.out.println("User " + set.getData().getId() + " " + set.getEvent());
        } else if (message instanceof PNSetDataSyncChannelEventMessage) {
            PNSetDataSyncChannelEventMessage set = (PNSetDataSyncChannelEventMessage) message;
            System.out.println("Channel " + set.getData().getId() + " " + set.getEvent());
        } else if (message instanceof PNSetDataSyncMembershipEventMessage) {
            PNSetDataSyncMembershipEventMessage set = (PNSetDataSyncMembershipEventMessage) message;
            System.out.println("Membership " + set.getData().getId() + " " + set.getEvent());
        } else if (message instanceof PNSetDataSyncEntityEventMessage) {
            PNSetDataSyncEntityEventMessage set = (PNSetDataSyncEntityEventMessage) message;
            System.out.println("Entity " + set.getData().getId() + " " + set.getEvent());
        } else if (message instanceof PNSetDataSyncRelationshipEventMessage) {
            PNSetDataSyncRelationshipEventMessage set = (PNSetDataSyncRelationshipEventMessage) message;
            System.out.println("Relationship " + set.getData().getId() + " " + set.getEvent());
        } else if (message instanceof PNDeleteDataSyncUserEventMessage) {
            PNDeleteDataSyncUserEventMessage deleted = (PNDeleteDataSyncUserEventMessage) message;
            System.out.println("User " + deleted.getId() + " deleted at " + deleted.getDeletedAt());
        } else if (message instanceof PNDeleteDataSyncChannelEventMessage) {
            PNDeleteDataSyncChannelEventMessage deleted = (PNDeleteDataSyncChannelEventMessage) message;
            System.out.println("Channel " + deleted.getId() + " deleted at " + deleted.getDeletedAt());
        } else if (message instanceof PNDeleteDataSyncMembershipEventMessage) {
            PNDeleteDataSyncMembershipEventMessage deleted = (PNDeleteDataSyncMembershipEventMessage) message;
            System.out.println("Membership " + deleted.getId() + " deleted at " + deleted.getDeletedAt());
        } else if (message instanceof PNDeleteDataSyncEntityEventMessage) {
            PNDeleteDataSyncEntityEventMessage deleted = (PNDeleteDataSyncEntityEventMessage) message;
            System.out.println("Entity " + deleted.getId() + " deleted at " + deleted.getDeletedAt());
        } else if (message instanceof PNDeleteDataSyncRelationshipEventMessage) {
            PNDeleteDataSyncRelationshipEventMessage deleted = (PNDeleteDataSyncRelationshipEventMessage) message;
            System.out.println("Relationship " + deleted.getId() + " deleted at " + deleted.getDeletedAt());
        } else {
            System.out.println("Unknown DataSync event of type " + message.getType());
        }
    }
});

subscription.subscribe();
```

Each event arrives as a `PNDataSyncEventResult`. Its `getExtractedMessage()` names the object kind in `getType()` (`user`, `channel`, `membership`, `entity`, or `relationship`) and carries the object state in `getData()`. A `create` or `update` event is a `PNSetDataSync*EventMessage` whose `getEvent()` is `CREATE` or `UPDATE`. For a `delete` event, a `PNDeleteDataSync*EventMessage` carries only the `getId()` and the `getDeletedAt()` timestamp.

`getType()` names the object kind directly, while the message class tells you which typed state container the event carries:

| Change to | `getType()` | On `create` or `update` | On `delete` |
| --- | --- | --- | --- |
| A user | `user` | `PNSetDataSyncUserEventMessage` with `PNDataSyncUserData` | `PNDeleteDataSyncUserEventMessage` |
| A channel | `channel` | `PNSetDataSyncChannelEventMessage` with `PNDataSyncChannelData` | `PNDeleteDataSyncChannelEventMessage` |
| An entity | `entity` | `PNSetDataSyncEntityEventMessage` with `PNDataSyncEntityData` | `PNDeleteDataSyncEntityEventMessage` |
| A membership | `membership` | `PNSetDataSyncMembershipEventMessage` with `PNDataSyncMembershipData` | `PNDeleteDataSyncMembershipEventMessage` |
| A relationship | `relationship` | `PNSetDataSyncRelationshipEventMessage` with `PNDataSyncRelationshipData` | `PNDeleteDataSyncRelationshipEventMessage` |

Branch on the message class with `instanceof` checks, and always add a final `else` branch, because an event the SDK does not recognize arrives as a `PNUnknownDataSyncEventMessage` that keeps the raw `getType()`, `getEvent()`, `getMetadata()`, and `getData()`. `getClassName()` tells you the specific class within a kind, for example which subclass of `User` an event belongs to.

### Where each event is delivered

The channels that receive an event depend on the changed object. A relationship or membership never publishes on a channel named after its own id:

| Change to | On `create` | On `update` or `delete` |
| --- | --- | --- |
| A user | The user's `id` | The user's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A channel | The channel's `id` | The channel's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| An entity | The entity's `id` | The entity's `id`, plus the `id` of every entity, user, or channel connected to it by a relationship or membership |
| A membership | **Both** the `userId` and the `channelId` of the membership | Same as `create` |
| A relationship | **Both** the `entityAId` and the `entityBId` of the relationship | Same as `create` |

:::note Update and delete also fan out to connected objects
An update or delete on a user, channel, or entity is also delivered on the `id` channel of every other object connected to it by a relationship or membership, in either direction, at the time of the change. A client subscribed to a connected object's channel receives the event too, even though that object itself did not change. A create does not fan out this way, because nothing can be connected to a brand new object yet.
The connected channels are entity, user, and channel ids. Relationships and memberships never get an id channel of their own, so they never appear in this fan-out as a channel name.
:::

So to see memberships appear and disappear for Alice, subscribe to `user-alice` rather than the membership id. A client subscribed to both sides of the same link receives the change twice, once per channel. Deduplicate create and update events on the object's `getId()` and `getUpdatedAt()`, and delete events on `getId()` and `getDeletedAt()`.

For a membership event, `PNDataSyncMembershipData` carries `getChannelId()` and `getUserId()` directly, so you don't map them onto generic A and B sides. A relationship event carries `getEntityAId()` and `getEntityBId()`.

### Projection channels

Each [projection](https://www.pubnub.com/docs/sdks/java/api-reference/access-manager.md#grant-token) declared on the class gets its own event, published to its own channel, and carrying only that projection's view of the payload:

| Projection | Channel | Payload |
| --- | --- | --- |
| `__default__` (the base projection) | The object's own id, for example `product-sneaker-42` | The fields tagged `__default__` |
| Any named projection, for example `admin` | `__<projection>__<id>`, for example `__admin__product-sneaker-42` | The fields tagged with that projection |

Filtering applies to `payload` and to `status`: each is included in a given projection's event only if the class declares it under that projection, falling back to `__default__` when the class never declares `status`. `id`, `eTag`, `createdAt`, `updatedAt`, and `expiresAt` are never filtered. Every projection's event carries them unchanged.

So one change to an object whose class declares an `admin` projection publishes two events, and a client subscribed only to `product-sneaker-42` never sees the `admin`-only fields:

```java
DataSyncEntity entity = pubnub.dataSyncEntity("product-sneaker-42");

Subscription defaultSubscription = entity.subscription();
Subscription adminSubscription = entity.subscription("admin");

defaultSubscription.subscribe();
adminSubscription.subscribe();
```

If the class declares no properties at all there is nothing to filter, so a single unfiltered event is published to the object's own id channel.

:::warning Projection channels need channel grants
Publishing to `__<projection>__<id>` is an ordinary channel publish, and it isn't gated by the projection assignments in a token. Use Access Manager channel grants to control who can subscribe to a projection channel. Anyone who can subscribe there receives the restricted fields. Refer to [Grant token](https://www.pubnub.com/docs/sdks/java/api-reference/access-manager.md#grant-token).
:::

Delete events are never filtered by a projection.

Events are off by default and are enabled per class in the [Admin Portal](https://admin.pubnub.com). Refer to [enabling events](https://www.pubnub.com/docs/data-storage/structured-data/events.md#enable-datasync-events) for how to turn them on, and [receiving events](https://www.pubnub.com/docs/data-storage/structured-data/events.md) for the listener flow.

Last updated at: 2026-10-08T04:47:34.000Z
