This project is read-only.

Creating an index

SimpleLucene has an index service (SimpleLucene.Impl.IndexService) that makes it easy to create and update a Lucene index.

The workflow is quite simple:
  1. Create an IIndexWriter. For file system indexes you can use the DirectoryIndexWriter. You must specify the index location. Note: A MemoryIndexWriter can be found in the tests project (for writing to an in-memory index)
  2. New up an IndexService, passing it an index writer. IndexService implements the IDisposable interface so you should call Dispose() when you are finished with it. This can be done implicitly via a using clause. When Dispose is called we commit and close the internal Lucene IndexWriter. You can also choose to optimize the index (click here for details).
  3. Call IndexEntities passing a collection of objects to index along with a delegate converter.

        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(), p => {
                    var doc = new Document();
                    doc.Add(new Field("id", p.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    doc.Add(new Field("name", p.Name, Field.Store.YES, Field.Index.ANALYZED));
                    return doc;
                });

                Console.WriteLine("{0} products indexed in {1} milliseconds.", result.Count, result.ExecutionTime);
                Console.ReadLine();
            }
        }

In the above example we pass a delegate function to the IndexEntities method that tells Lucene how we convert our entity to a Lucene document.

The IndexEntities(...) returns an IndexResult object that gives us some basic statistics about the indexing operation.

To get a good understanding of Lucene documents I would recommend reading the "Lucene In Action" book by Manning. It's for the Java version of Lucene but the APIs are virtually identical.

Last edited Feb 5, 2011 at 10:02 PM by retroviz, version 2

Comments

No comments yet.