SLN
SLN

Reputation: 5092

Azure CosmosDB get pagination data by a specific page number

Background: FastAPI + CosmosDB

The official pagination code example for the CosmosDB python SDK is show below. It only shown how to get the next page via page iterator. How can I get the pagination data by a specific page number?

 def test_paging_with_continuation_token(self):
    created_collection = self.config.create_multi_partition_collection_with_custom_pk_if_not_exist(self.client)

    document_definition = {'pk': 'pk', 'id': '1'}
    created_collection.create_item(body=document_definition)
    document_definition = {'pk': 'pk', 'id': '2'}
    created_collection.create_item(body=document_definition)

    query = 'SELECT * from c'
    query_iterable = created_collection.query_items(
        query=query,
        partition_key='pk',
        max_item_count=1
    )
    pager = query_iterable.by_page()
    pager.next()
    token = pager.continuation_token
    second_page = list(pager.next())[0]

    pager = query_iterable.by_page(token)
    second_page_fetched_with_continuation_token = list(pager.next())[0]

    self.assertEqual(second_page['id'], second_page_fetched_with_continuation_token['id'])

Upvotes: 0

Views: 1576

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136356

For pagination by specific page number, you can make use of OFFSET LIMIT clause available in Cosmos DB SQL API.

All you need to do is specify the offset and limit clause in your query itself. Something like:

query = 'SELECT * from c OFFSET 1 LIMIT 1'

However, please note that using OFFSET/LIMIT increases RU consumption considerably. From the same link:

The RU charge of a query with OFFSET LIMIT will increase as the number of terms being offset increases. For queries that have multiple pages of results, we typically recommend using continuation tokens. Continuation tokens are a "bookmark" for the place where the query can later resume. If you use OFFSET LIMIT, there is no "bookmark". If you wanted to return the query's next page, you would have to start from the beginning.

Upvotes: 3

Related Questions