Thursday, October 18, 2012

Use CAML when searching SharePoint

CAML is worth the effort. I went from this (powershell):

$listitem = $list.Items | Where { ($_.Title -eq $row["Title"]) -and ($_.Name -eq $row["Name"]) }

To this:
$query = New-Object Microsoft.SharePoint.SPQuery 
$caml = '<where><and><eq><fieldref name="Title"><value type="Text">' + $row["Title"] + '</value></fieldref></eq><eq><fieldref name="Name"><value type="Text">' + $row["Name"] + '</value></fieldref></eq></and></where>'
$query.Query = $caml 
$listitem = $list.GetItems($query)[0]
And the code in question is now about 60 times faster. I’m guessing that the first line is scanning every item until it finds the one it wants, while the CAML query somehow avoids that. Big improvement.