Adding custom fields to the search index

Sometimes you want to filter your searches on a property that doesn't have a field in the Lucene search index. This example will show you how to add a property as a custom field.

Step 1: Add custom field

In the partial class to the content class in question(in App_Code/WAF_Custom/namespace/ folder), override the BuildSearchIndex method like this:

 

public override void BuildSearchIndex(Lucene.Net.Documents.Document doc) {
        base.BuildSearchIndex(doc);
        doc.Add(new Field("PublishYear", this.PublishDate.Year.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
        doc.Add(new Field("PublishMonth", this.PublishDate.Month.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));        
 }

Step 2: Using the custom field in a search

string strYear = "2009"; //this should be changed to the correct year
string strMonth = "5"; //this should be changed to the correct month

BooleanQuery bq = new BooleanQuery();

bq.Add(new TermQuery(new Term("PublishYear", strYear)), BooleanClause.Occur.MUST);
bq.Add(new TermQuery(new Term("PublishMonth", strMonth)), BooleanClause.Occur.MUST);
indexQuery.CustomQuery = bq;