Tuesday, December 7, 2010

EasySearch – Creating a custom index handler

Lately, I’ve spent quite a lot of time figuring out EasySearch. There is a developer guide available, but sadly it is quite messy and brief. So in this blog post I’ll show you how to create a custom index handler in order to add a creation year field to your Lucene document.

The first thing we need to do is to create a custom index handler class. This class needs to inherit from the NetworkedPlanet.EasySearch.Lucene.IIndexHandler interface, which means it needs two methods: IndexFile(…) and IndexPage(…):

public class CustomIndexHandler : IIndexHandler

{

  public CustomIndexHandler(){}

  public bool IndexPage(PageData page, Document luceneDoc)

  {

    AddYearField(page, luceneDoc);

    return true; // returns true, because this method should never block the indexing of a file

  }

 

  public bool IndexFile(UnifiedFile file, Document luceneDoc)

  {

    return true; // returns true, because this method should never block the indexing of a file

  }

 

  private void AddYearField(PageData page, Document luceneDoc)

  {

    // Add the last modified date of the file to a field named

    // "modified". Use a field that is indexed (i.e., searchable),

    // but don't tokenize the field into words.

    luceneDoc.Add(new Field("creationYear", DateTools.TimeToString(page.Created.Ticks, DateTools.Resolution.YEAR), Field.Store.YES, Field.Index.UN_TOKENIZED));

  }

}

The AddYearField adds a new “creationYear” field to the Lucene document. This field is given a year value, such as 2008, 2009, 2010. In order to invoke the index handler before the Lucene document is indexed in Lucene we need to register it in the <indexconfiguration> section in web.config:

<lucene:configuration>

  <lucene:indexhandler Type="MyProject.CustomIndexHandler, MyProject"/>

</lucene:configuration>

It’s as easy as that! You can now use the creationYear field in the Lucene document in a facet or in any other way you need.

Happy coding!

3 comments:

  1. Thank you!
    Exactly what I was looking for :)
    Agreed with your comment about the developer guide.

    ReplyDelete
  2. You're welcome, I'm glad I could help :)

    ReplyDelete
  3. Nice article, can you post - what do I need to implement to create GIS indexer

    ReplyDelete