Using Caml Queries To Retrieve Items From Sharepoint Document Libraries

Accessing Documents with CAML Queries

Collaborative Application Markup Language (CAML) queries allow developers to retrieve items from SharePoint lists and document libraries in a precise and efficient manner. By crafting a CAML query, users can filter, sort, and limit the results to include just the items they need.

The CAML language contains specifically defined XML elements and attributes that formulate a query describing the desired set of results. When executed through the SharePoint Client Object Model, a CAML query will return a collection of matching list items.

Using CAML queries enables directly accessing documents rather than having to load entire lists and filter through them client-side. This improves performance for large document libraries.

Defining CAML and its Use Cases

What is CAML (Collaborative Application Markup Language)

Collaborative Application Markup Language (CAML) is an XML schema used to construct queries and operations for the SharePoint platform. It allows performing reads and writes to SharePoint lists and libraries in a structured and efficient way.

In CAML, the <Query> element contains a request for items from a list or library. Elements like <Where>, <OrderBy>, and <ViewFields> enable filtering, sorting, and selecting specific fields in the result set.

Additional CAML elements define other operations like creating, deleting, or updating items and handling grouping, lookups, and queries across site collections.

When serialized into a string, a CAML query can be passed to SharePoint Client Object Model API methods to retrieve or modify data.

Common Scenarios for Using CAML Queries

Some common use cases where CAML queries are helpful include:

  • Filtering documents by property – Retrieving files uploaded in the past week, documents with specific meta-data values, etc.
  • Search without full-text search enabled – Locating documents by name/title or other string properties
  • Sorting and pagination – Ordering documents by properties and retrieving in digestible page sizes
  • Strict querying on multi-value fields – CAML enables exact matches on people/lookup columns with multiple values
  • Field selection – Choosing specific fields in the query output improves performance over entire list items
  • Batch operations – Updating/deleting multiple items matching specific conditions

Crafting CAML Queries

CAML Query Structure

A CAML query contains a root <Query> element, with child elements specifying various parameters to filter, sort, and define fields in the result set. Here is an overview of key elements:

  • <Where> – Boolean filter condition(s) to select matching items
  • <OrderBy> – Fields to sort by, in ascending or descending order
  • <ViewFields> – Columns to include for each returned list item
  • <RowLimit> – Maximum rows to return, for pagination

These elements contain further nesting and parameters that construct the logic and syntax for the query request.

Filtering by Document Properties

The <Where> element enables filtering items by values in certain fields/columns. Common approaches include:

  • Text filter – Match text strings in text fields:
    <Where>
       <Contains>
          <FieldRef Name="Title"/>
          <Value Type="Text">sample</Value>
       </Contains>
    </Where>
  • Comparison operators – Fields using <Eq>, <Gt>, <Lt> for equals, greater than, less than
  • Data ranges – Date fields filtered between dates:
    <Where>
       <And>
          <Geq>
             <FieldRef Name="Created"/>
             <Value Type="DateTime">2023-02-01T00:00:00Z</Value>
          </Geq>
          <Leq>    
             <FieldRef Name="Created"/>
             <Value Type="DateTime">2023-02-07T00:00:00Z</Value>
          </Leq>
       </And>
    </Where>

Sorting and Limiting Results

The <OrderBy> node specifies the fields to sort by in ascending or descending order:

<OrderBy>
   <FieldRef Name="Created" Ascending="FALSE"/> 
</OrderBy>

The <RowLimit> element defines the maximum count of items to return in the CAML query, enabling pagination:

<RowLimit>50</RowLimit>

Example Query to Retrieve Documents by Title

Here is an example CAML query that selects 10 documents, sorted by Created date, where the Title contains “Strategy”:

<Query>
   <Where>
      <Contains>
         <FieldRef Name="Title"/>  
         <Value Type="Text">Strategy</Value>
      </Contains>
   </Where>
   <OrderBy>
      <FieldRef Name="Created" Ascending="FALSE"/>
   </OrderBy>
   <RowLimit>10</RowLimit>
</Query>

Executing CAML Queries in SharePoint

Using Client Object Model

To run CAML queries in SharePoint, the Client Object Model (COM) contains relevant methods like:

  • List.GetItems() – Retrieve list items matching CAML query
  • ListItemCollection.Add() – Insert new items based on CAML batch operation
  • ListItemCollection.Update() – Update existing items using CAML

These methods accept serialized CAML strings defining queries and changes to enact.

Calling SP.Web.GetItems Method

For example, calling the SP.Web.GetItems() method executes a CAML query string, and returns a collection of matching list items:

var query = "<Query>...</Query>"; 

var items = SP.Web.GetItems(query);

The CAML query XML is passed in as a parameter, specifying filters, sorting, fields, and limits.

Handling the Result Set

The returned object contains Properties and field values for each list item matching the CAML query conditions. These can be enumerated and processed as needed:

var itemEnum = items.getEnumerator();

while (itemEnum.moveNext()) {   
   var item = itemEnum.get_current();
   
   // Read field values
   console.log(item.get_item("Title")); 
} 

Any errors in the CAML syntax or query execution will bubble up to be handled appropriately.

Considerations and Best Practices

Performance Optimizations

For better performance, optimize CAML queries by:

  • Filter narrow result sets first with <Where> to avoid sorting/filtering all items
  • Restrict returned fields with <ViewFields> instead of full list items
  • Set row limits for pagination to keep result set smaller
  • Avoid unneeded joins against secondary lists

Accounting for Null Values

Check for null values to avoid errors like:

<IsNotNull>
   <FieldRef Name="StartDate"/> 
</IsNotNull>

Handling Errors Gracefully

Wrap CAML queries in try/catch blocks, check the request status, and handle issues like:

try {

   var items = SP.Web.GetItems(query);

   // Check request status
   if(items.get_statusCode() !== 0 ) {
      throw "Error in query execution: " + items.get_statusCode(); 
   }   

} catch(error) {   
   console.log("Error with CAML query: " + error);

}

Leave a Reply

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