Using Index Definitions

In the previous example we passed a delegate converter function to our IndexService.IndexEntities method to convert our entities to Lucene documents.

This method is okay for indexing very simple entities but in most cases I would recommend using Index Definitions.

As the name suggests, an Index Definition defines how we index a specific type of object.

To create a definition, you should implement IIndexDefinition<T> where T is the type you wish to index.

Below is a definition for the Product class we are using in these examples:

    public class ProductIndexDefinition : IIndexDefinition<Product> {
        public Document Convert(Product entity)
            var document = new Document();
            document.Add(new Field("id", entity.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("name", entity.Name, Field.Store.YES, Field.Index.ANALYZED));
            document.Add(new Field("createdon", DateTools.DateToString(entity.CreatedOn, DateTools.Resolution.DAY),
                     Field.Store.YES, Field.Index.NOT_ANALYZED));
            var priceField = new NumericField("price", Field.Store.NO, true);
            return document;

        public Term GetIndex(Product entity) {
            return new Term("id", entity.Id.ToString());

The IIndexDefinition interface requires that you return a Lucene Term for the identifier of your object. This is necessary when we re-index entities so we can locate the existing document in the index.

We can then update the code from the previous example to use our index definition instead:

        static void Main(string[] args)
            // index location
            var indexPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Index");
            var indexWriter = new DirectoryIndexWriter(new DirectoryInfo(indexPath), true);

            using (var indexService = new IndexService(indexWriter)) {
                var result = indexService.IndexEntities(ProductRepository.GetProducts(), new ProductIndexDefinition());
                Console.WriteLine("{0} products indexed in {1} milliseconds.", result.Count, result.ExecutionTime);

Last edited Feb 6, 2011 at 2:37 PM by retroviz, version 6


No comments yet.