nhibernatelucene.netnhibernate.search

Easiest way to reindex lucene.net indexes when nhibernate.search used?


Context =>
Calling wcf, some random stored procedures and sql stuff theoretically imports some data.

Requirements =>
Reindex lucene indexes for some of imported entities.

Question =>
What's the easiest way to do that?

Theoretically, if nhibernate is initialized, nhibernate.search should be aware which entities are supposed to be indexed. Therefore - i was wondering, are there any ready to use tools/whatnot to fulfill my requirement?


Is this the only way?


Solution

  • My quick and dirty approach =>

     public static class LuceneReindexer
        {
            public static void Run()
            {    
                var entityTypes = typeof(FooEntity).Assembly.GetTypes()
                    .Where(x => x.BaseType == typeof(Entity)
                        || x.BaseType == typeof(KeyedEntity));
    
                foreach (var t in entityTypes)
                    if (TypeDescriptor
                       .GetAttributes(t)[typeof(IndexedAttribute)] != null)
                          ReindexEntity(t);
            }
    
            private static void ReindexEntity(Type t)
            {
                var stop = false;
                var index = 0;
                const int pageSize = 500;
    
                do
                {
                    var list = NHibernateSession.Current.CreateCriteria(t)
                        .SetFirstResult(index)
                        .SetMaxResults(pageSize).List();
    
                    NHibernateSession.Current.Transaction.Begin();
                    foreach (var itm in list)
                        NHibernateSession.Current.Index(itm);
                    NHibernateSession.Current.Transaction.Commit();
    
                    index += pageSize;
                    if (list.Count < pageSize) stop = true;
                } while (!stop);
            }
        }
    

    No ideas about transaction and paging part (and don't care at the moment). Kind a does what i needed. :D