Monday, April 28, 2014

Sitecore: Set Up New Lucene Index and Search Result Class

Background

Lucene is great when you don't want to implement Solr.  Sure, it is not as powerful as Solr nor does it do faceting, but for all simple searches that return results, Lucene does the job well.  Both utilize the concept of creating indexes and querying for results against the indexes.


Requirements

Out-of-the-box, Sitecore defined indexes for general items like the content node, the media library, and templates across all three databases.  I am sure you can query the content node of the master database to get anything you want but you don't have to.  A better way is to create indexes that are less general and more specific and tailored to your needs. 


Set Up New Index

The general master database index is defined here:

Sitecore.ContentSearch.Lucene.Index.Master.config

The smaller indexes are boken down and defined here:

Sitecore.ContentSearch.Lucene.Indexes.Sharded.Master.config

If you want to define a new smaller index for the master database, this is where it should be defined.

Add a new index definition like this:



Here you will see that a custom crawler has been used.  You can refer to an older posting for more details about setting up custom crawlers:

http://mrstevenzhao.blogspot.com/2014/04/sitecore-custom-item-crawler.html

At this point, if you go to Sitecore admin control panel, you will see this new index listed when you navigate to the section for rebuilding indexes.



Set Up New Search Result Class

Sitecore has a BuilInFields class that contains index field names of general fields.  We can use those index fields to create a base class that only contains fields we care about.  Lets create one right now:




Please remember that all search result classes have to inherit from the SearchResultItem class which gives you even more fields and methods already defined there.

Now, we can create more custom classes based on top of the base result item class we just created.  Let's create one:



Keep in mind that Fields is just a static mapping class that stores key-value pairs for index field names.  Since these two new fields are not standard fields, we have to define these two new fields in the configuration file, Sitecore.ContentSearch.Lucene.DefaultIndexConfiguration.config.  Add this to the <fieldNames> section:



Now, Lucene knows about these two new fields and where to store the indexed values under.  Rebuild the index and the values for these new fields will be available to query against.




Summary

It is quite easy and beneficial to add new indexes.  If you add custom fields in your templates that need to be indexed, you would have to create custom indexes and search result classes to handle the new fields.  Also, you can isolate your queries away from the main master database index which also speeds up your queries and speeds up index rebuilds as well.

No comments:

Post a Comment