Selecting media using Razor = Slow Performance. Examine to the rescue

alternative razor code to select Media Items.

Posted on Sunday, March 01, 2015


Requirement was to list the last 10 documents added to the Media library and order them from newest first. Straight forward we thought.

So using razor syntax in a partial macro file:

var docsInLibrary = Umbraco.AncestorsOrSelf().Descendants().Where("includeInLibrarySearch").OrderBy("createDate desc").Take(10);


<ul >
@foreach(var file in docsInLibrary )
<li><a href="@file.Url">@file.Name</a></li>

(the "includeInLibrarySearch" is a true/false datatype allowing the editor to tag the documents in the media library to be included in the search)

This worked fine in development environment, typically there was less than 100 items in the media library. So the page loaded no problem.
As the editors set to work on loading content to the site, the page running this script became very slow, we then "cached" the query - which was ok except the first load of the page was taking 10+seconds to load. The documents numbers in the media section was now over 2,000+.

Enter Examine....

On reading forum posts on , stackoverflow and twitter posts, we turned to using Examine which returns results very quickly. Examine is based on Lucene so results and searching the index is blisteringly fast once we switched  the code, the page which was creaking and loading in 10 plus seconds now loaded in a blink of the eye.

The partial view macro script is listed below:

@inherits Umbraco.Web.Macros.PartialViewMacroPage
@using Examine
@using Examine.SearchCriteria
@using Examine.LuceneEngine.SearchCriteria

var Searcher = ExamineManager.Instance.SearchProviderCollection["InternalSearcher"];
var searchCriteria = Searcher.CreateSearchCriteria(UmbracoExamine.IndexTypes.Media);
var filter = searchCriteria.Field("includeInLibrarySearch","1").Compile();
var results = Searcher.Search(filter).OrderByDescending(x => x.Fields["createDate"]).Take(10);

<h1>Recently Published</h1>
<ul class="libraryLinks">
@foreach (Examine.SearchResult result in results)
<a href="@result.Fields["umbracoFile"]">@result.Fields["nodeName"]</a>


 Hope this helps. Tested on 6.3 and 7.1 umbraco.