Orphans sites causing search to fail

Search results not returned and instead throw a correlation id error with below error found in ULS

 

############  0x5304  SharePoint Server Search     Query    afpkb     Unexpected        Getting results failed: System.NullReferenceException: Object reference not set to an instance of an object.     at Microsoft.Office.Server.Search.Administration.UrlMapper.ExtractMapping(Pair`2 properties, SPSite site, IDictionary`2 urlMapping, IDictionary`2 reverseUrlMapping)      at Microsoft.Office.Server.Search.Administration.UrlMapper.GetNewCacheEntry(Pair`2 properties)     at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)     at Microsoft.Office.Server.Search.Administration.UrlMapper.GetUrlMapping(QueryProperties properties)     at Microsoft.Office.Server.Search.Administration.SearchServiceApplicationProxy.Execute(QueryProperties properties)     at Microsoft.Office.Server.Search.Query.Query.ExecuteQuery()     at Microsoft.Office.Server.Search.Query.SearchExecutor.ExecuteQueryInternal(Query query)     at Microsoft.Office.Server.Search.Query.SearchExecutor.ExecuteQuery(Query query)     at Microsoft.Office.Server.Search.Query.SearchExecutor.ExecuteQueries(Dictionary`2 queries, Boolean handleExceptions)     at Microsoft.Office.Server.Search.WebControls.ScriptApplicationManager.GetSyncResult(String queryGroupName)     at Microsoft.Office.Server.Search.WebControls.DataProviderScriptWebPart.GetInitialResult()               91904c9d-8187-a049-6136-3aa5f371c168

 

This is caused due to orphan sites in Content Db/Sharepoint Config DB.

Resolution

  1. First just detect orphans-

 

$CDBs = Get-SPContentDatabase

ForEach ($CDB in $CDBs)

{

Write-Host "Detecting Orphans for " $CDB.Name

$CDB.Repair($false)

}

 

2.  Once these have been detected go ahead and rerun the commands by setting $CDB.Repair($true) for the specific content Database only

 

3. Also refresh the particular database in config DB by running-

 

 

$db = Get-SPDatabase | where {$_.Name -eq "DatabaseName"}

$db.RefreshSitesInConfigurationDatabase()