开发者

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

开发者 https://www.devze.com 2022-12-20 09:41 出处:网络
Context => Calling wcf, some random stored procedures and sql stuff theoretically imports some data. Requirements =>

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 -开发者_StackOverflow中文版 i was wondering, are there any ready to use tools/whatnot to fulfill my requirement?


Is this the only way?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号