SharePoint CAML paging with CSOM

When you are querying a big bunch of list items you should consider to use paging functionalities. For example you could download 2000 items within ten separate requests were each one queries a bulk of 200 items.

This will spare the server performance and speeds up the transfer over the wire. When downloading all items at once can lead to a time-out for example.

You can control the paging process by using a ListItemCollectionPosition object in the CamlQuery.

Here is an example where we query all items with a defined content type ID in the pages list in bunches of 100 items each:

private void QueryItems(List pages, ListItemCollectionPosition position = null)
{
    var query = new CamlQuery
    {
        ListItemCollectionPosition = position,
        ViewXml =
            @"<View Scope='RecursiveAll'>
                <QueryOptions><ViewAttributes Scope='Recursive'/></QueryOptions>
                <RowLimit>100</RowLimit>
                <Query>
                    <Where>
                        <Eq>
                            <FieldRef Name='ContentTypeId'/>
                            <Value Type='ContentTypeId'>{0}</Value>
                        </Eq>
                    </Where>
                </Query>
            </View>".FormatWith(ContentTypeId)
    };

    var items = pages.GetItems(query);
    Client.Load(items);
    Client.ExecuteQuery();

    foreach (var item in items)
    {
        // Do something with the item
    }
    if (items.ListItemCollectionPosition != null)
    {
        QueryItems(pages, items.ListItemCollectionPosition);
    }
}

The bulk size is being defined in the Query XML by using the RowLimit block. When iterating through the collection of items the current position will be saved in the ListItemCollectionPosition property. This property can be reused in the next query (in this implementation it is used recursive until there are no items left).

When the position argument is null the query will start from beginning (e.g. taking the first 100 items).

You can also control the paging mechanism manually by manipulating the PagingInfo property of the ListItemCollectionPosition. This could look like this: Paged=TRUE&p_SortBehavior=0&p_ID=148

This means at first that paging is activated. Second it defines that the last queried object has the ID 148. So on the next recursive method call the CAML query will take the next 100 items starting with ID 149.

Leave a Reply

Your email address will not be published. Required fields are marked *

one × 1 =