-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Added Samples for Feed Range APIs #45166
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
andrewmathew1
merged 8 commits into
Azure:main
from
andrewmathew1:users/andrewmathew1/feedrangeapisamples
Jul 8, 2026
+1,223
−0
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3df21fd
added samples for feed range apis
cb7a440
updated sample delete
3716b19
updated feedrange doc to have async get_latest_session_token()
e92df24
Update sdk/cosmos/azure-cosmos/samples/README.md
andrewmathew1 1f06056
added pr suggestions
de13b00
added continuation token samples
bf06d06
Merge branch 'main' into users/andrewmathew1/feedrangeapisamples
simorenoh 1dda22a
Merge branch 'main' into users/andrewmathew1/feedrangeapisamples
andrewmathew1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| # Feed Ranges in the Python SDK for Azure Cosmos DB | ||
|
|
||
| ## What Are Feed Ranges? | ||
|
|
||
| A feed range is an opaque representation of a scope within a container, defined by a contiguous range of partition key hash values. Feed ranges are a flexible way to represent partitioning at different levels of granularity: | ||
|
|
||
| - **Entire container** – A single feed range can span the full hash range, covering all data in the container. | ||
| - **Physical partition** – Each feed range returned by `read_feed_ranges()` corresponds to one physical partition. The full set covers the entire container without overlap, and every item belongs to exactly one feed range. | ||
| - **Specific partition key value** – A feed range can represent the narrow hash range for a single partition key, obtained via `feed_range_from_partition_key()`. | ||
|
|
||
| In all cases, a feed range is just another way to express a scope within a container's partition key hash space. | ||
|
|
||
| For general information about partitioning, see: | ||
| - [Partitioning overview](https://learn.microsoft.com/azure/cosmos-db/partitioning-overview) | ||
| - [Partition Keys in the Python SDK](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/docs/PartitionKeys.md) | ||
|
|
||
| > **Important:** Feed ranges are returned as `dict[str, Any]` values and must be treated as opaque. | ||
| > Do **not** manually construct, parse, or depend on the internal structure of a feed range dictionary. | ||
| > Use only the container methods described below to create, compare, and consume feed ranges. | ||
|
|
||
| --- | ||
|
|
||
| ## Feed Ranges vs. Partition Keys | ||
|
|
||
| Feed ranges and partition keys both define a scope within a container, but they operate at different levels: | ||
|
|
||
| | | Partition Key | Feed Range | | ||
| |---|---|---| | ||
| | **Granularity** | A single logical partition (one partition key value) | Zero, one, or many logical partitions (a hash range) | | ||
| | **Source** | Defined by your data model; you supply the value | Returned by `read_feed_ranges()` or derived from a partition key | | ||
| | **Relationship** | A partition key maps to exactly one feed range | A feed range can contain multiple partition keys | | ||
| | **Use case** | Point reads, single-partition queries | Parallel processing, scoped change feed, workload distribution | | ||
|
|
||
| You can convert between them: | ||
| ```python | ||
| # Partition key → Feed range | ||
| feed_range = container.feed_range_from_partition_key("my_partition_key") | ||
|
|
||
| # Check which container feed range contains a partition key's feed range | ||
| for container_fr in container.read_feed_ranges(): | ||
| if container.is_feed_range_subset(container_fr, feed_range): | ||
| print("Partition key belongs to this feed range") | ||
| break | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## When to Use Feed Ranges | ||
|
|
||
| | Scenario | Description | | ||
| |----------|-------------| | ||
| | **Parallel query processing** | Read all feed ranges, then query each range independently across multiple workers. Each worker processes a non-overlapping subset of the data. | | ||
| | **Scoped change feed** | Consume the change feed for a specific feed range rather than the entire container, enabling fan-out architectures for change processing. | | ||
| | **Workload distribution** | Assign feed ranges to different threads, processes, or machines to distribute work evenly across a container's data. | | ||
| | **Session token management** | Track session tokens per feed range for fine-grained session consistency when managing your own session tokens across multiple clients. | | ||
| | **Partition key to feed range mapping** | Convert partition key values to feed ranges to determine which worker or scope a specific partition key belongs to. | | ||
|
|
||
| --- | ||
|
|
||
| ## API Reference | ||
|
|
||
| ### `read_feed_ranges()` | ||
|
|
||
| Returns all feed ranges for the container. The number of feed ranges corresponds to the number of physical partitions. | ||
|
|
||
| ```python | ||
| # Sync | ||
| feed_ranges = list(container.read_feed_ranges()) | ||
|
|
||
| # Async | ||
| feed_ranges = [fr async for fr in container.read_feed_ranges()] | ||
| ``` | ||
|
|
||
| **Parameters:** | ||
| - `force_refresh` *(bool, optional)* – When `True`, refreshes the cached partition key ranges before returning. Use this after a known partition split. Default: `False`. | ||
|
|
||
| **Returns:** `Iterable[dict[str, Any]]` (sync) / `AsyncIterable[dict[str, Any]]` (async) | ||
|
|
||
| --- | ||
|
|
||
| ### `feed_range_from_partition_key()` | ||
|
|
||
| Converts a partition key value to its corresponding feed range. Useful for determining which feed range a specific partition key belongs to. | ||
|
|
||
| ```python | ||
| # Sync | ||
| feed_range = container.feed_range_from_partition_key("Seattle") | ||
|
|
||
| # Async | ||
| feed_range = await container.feed_range_from_partition_key("Seattle") | ||
| ``` | ||
|
|
||
| **Parameters:** | ||
| - `partition_key` *(PartitionKeyType)* – The partition key value. If set to `None`, returns the feed range for partition keys with JSON null. See [Partition Keys](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/docs/PartitionKeys.md) for supported value types. | ||
|
|
||
| **Returns:** `dict[str, Any]` | ||
|
|
||
| --- | ||
|
|
||
| ### `is_feed_range_subset()` | ||
|
|
||
| Checks whether one feed range is fully contained within another. Common use cases include: | ||
|
|
||
| - **Partition key → worker routing**: After converting a partition key to a feed range with `feed_range_from_partition_key()`, determine which container-level feed range (and therefore which worker) owns that partition key. | ||
| - **Validating feed range assignments**: In fan-out architectures, verify that a previously stored feed range is still covered by one of the container's current feed ranges after a partition split. | ||
| - **Merging or grouping work**: When redistributing workload, check whether a smaller feed range falls within a larger one to decide if they can be handled together. | ||
|
|
||
| ```python | ||
| # Sync | ||
| is_subset = container.is_feed_range_subset( | ||
| parent_feed_range=container_feed_range, | ||
| child_feed_range=pk_feed_range | ||
| ) | ||
|
|
||
| # Async | ||
| is_subset = await container.is_feed_range_subset( | ||
| parent_feed_range=container_feed_range, | ||
| child_feed_range=pk_feed_range | ||
| ) | ||
| ``` | ||
|
|
||
| **Parameters:** | ||
| - `parent_feed_range` *(dict[str, Any])* – The feed range to test as the superset. | ||
| - `child_feed_range` *(dict[str, Any])* – The feed range to test as the subset. | ||
|
|
||
| **Returns:** `bool` – `True` if the child feed range is fully contained within the parent. | ||
|
|
||
| --- | ||
|
|
||
| ### `query_items()` with `feed_range` | ||
|
|
||
| Scopes a SQL query to a specific feed range. This is useful for parallel query execution where each worker queries a different feed range. | ||
|
|
||
| ```python | ||
| # Sync | ||
| items = list(container.query_items( | ||
| query="SELECT * FROM c WHERE c.status = 'active'", | ||
| feed_range=feed_range | ||
| )) | ||
|
|
||
| # Async | ||
| items = [item async for item in container.query_items( | ||
| query="SELECT * FROM c WHERE c.status = 'active'", | ||
| feed_range=feed_range | ||
| )] | ||
| ``` | ||
|
|
||
| > **Note:** `feed_range` and `partition_key` are **mutually exclusive** parameters. | ||
| > Providing both will raise a `ValueError`. | ||
|
|
||
| --- | ||
|
|
||
| ### `query_items_change_feed()` with `feed_range` | ||
|
|
||
| Scopes change feed consumption to a specific feed range. This enables fan-out architectures where each worker processes changes for a non-overlapping subset of the container. | ||
|
|
||
| ```python | ||
| # Sync | ||
| response = container.query_items_change_feed( | ||
| feed_range=feed_range, | ||
| start_time="Beginning" | ||
| ) | ||
| for item in response: | ||
| process(item) | ||
|
|
||
| # Async | ||
| response = container.query_items_change_feed( | ||
| feed_range=feed_range, | ||
| start_time="Beginning" | ||
| ) | ||
| async for item in response: | ||
| process(item) | ||
| ``` | ||
|
|
||
| > **Note:** `feed_range`, `partition_key`, and `partition_key_range_id` are **mutually exclusive** parameters. | ||
|
|
||
| --- | ||
|
|
||
| ### `get_latest_session_token()` | ||
|
|
||
| Gets the most up-to-date session token for a specific feed range from a list of session token and feed range pairs. This is a **provisional** API intended for advanced session token management scenarios. | ||
|
|
||
| ```python | ||
|
andrewmathew1 marked this conversation as resolved.
|
||
| # Sync | ||
| session_token = container.get_latest_session_token( | ||
| feed_ranges_to_session_tokens=[(feed_range, token), ...], | ||
| target_feed_range=target_feed_range | ||
| ) | ||
|
|
||
| # Async (must be awaited) | ||
| session_token = await container.get_latest_session_token( | ||
| feed_ranges_to_session_tokens=[(feed_range, token), ...], | ||
| target_feed_range=target_feed_range | ||
| ) | ||
| ``` | ||
|
|
||
| > **Note:** In the async client, `get_latest_session_token()` is a coroutine and **must be awaited**. | ||
|
|
||
| See the [session_token_management.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/session_token_management.py) (sync) and [session_token_management_async.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/session_token_management_async.py) (async) samples for complete examples. | ||
|
|
||
| --- | ||
|
|
||
| ## Important Considerations | ||
|
|
||
| ### Feed Ranges Are Opaque | ||
| Feed ranges are returned as `dict[str, Any]`. Their internal structure may change between SDK versions. Always use the provided API methods rather than constructing or parsing feed range dictionaries. | ||
|
|
||
| ### Serialization for Storage | ||
| If you need to persist feed ranges (e.g., to assign ranges to workers across restarts), you can safely serialize them with `json.dumps()` and deserialize with `json.loads()`: | ||
|
|
||
| ```python | ||
| import json | ||
|
|
||
| # Serialize for storage | ||
| serialized = json.dumps(feed_range) | ||
|
|
||
| # Deserialize for later use | ||
| feed_range = json.loads(serialized) | ||
| ``` | ||
|
|
||
| ### Partition Splits and Stale Feed Ranges | ||
| As your container's data grows, physical partitions may split, changing the set of feed ranges. The SDK handles stale feed ranges gracefully: | ||
|
|
||
| - **Queries with `feed_range`**: The SDK automatically resolves stale feed ranges and routes the query correctly. | ||
| - **Change feed with `feed_range`**: The SDK detects "feed range gone" conditions and transparently handles the split. | ||
| - **To get updated feed ranges**: Call `container.read_feed_ranges(force_refresh=True)`. | ||
|
|
||
| ### Mutual Exclusivity | ||
| When using feed ranges with `query_items()` or `query_items_change_feed()`, the `feed_range` parameter is mutually exclusive with `partition_key` (and `partition_key_range_id` for change feed). Providing both will raise a `ValueError`. | ||
|
|
||
| --- | ||
|
|
||
| ## Samples | ||
|
|
||
| For complete, runnable examples, see: | ||
| - [feed_range_management.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/feed_range_management.py) – Sync sample covering all feed range operations | ||
| - [feed_range_management_async.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/feed_range_management_async.py) – Async sample with `asyncio.gather()` for parallel processing | ||
| - [session_token_management.py](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/session_token_management.py) – Session token management using feed ranges | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.