Querying Sitecore 7 using the IndexField attributes

Below is example code on how to search the default index that sitecore sets up out of the box. It will automatically read the IndexField attribute off the class or use the lowercase version of the property name if no IndexField attribute is found.

// the index lives in the app_data folder, so using a Server.MapPath to get the real path for Lucene.
string searchIndexPath = Server.MapPath(Settings.IndexFolder + @"/lucinq_web_index");
using (SitecoreSearch search = new SitecoreSearch(searchIndexPath))
{
     ISitecoreQueryBuilder queryBuilder = new SitecoreQueryBuilder(SitecoreMode.Sitecore7);
     queryBuilder.TemplateId(ContentIds.HomeTemplateId); // add template id to the query
     // below users the sitecore index field attribute, its the same as 
     // queryBuilder.Term("_content", "value");
     queryBuilder.Term<SearchResultItem>(t => t.Content, "value");// set up the term based on the in built sitecore 7 class.
     ISitecoreSearchResult searchResult = search.Execute(qb);
     int totalResults = searchResult.TotalHits; // gets the total number of results
     List<Item> items = searchResult.GetPagedItems(1, 10);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s