以前做过 Hibernate Search的重建索引,就是老老实实的把所有的Mapped Class 找出来,
然后一个Class一个Class的找每个对象进行reindex,代码很长,写的很累。如下,先找到
所有的Class,
public void reindex() {
Session session = getSession();
FullTextSession fullTextSession = Search.getFullTextSession( session);
fullTextSession.setFlushMode(FlushMode.MANUAL);
fullTextSession.setCacheMode(CacheMode.IGNORE);
Transaction tx = fullTextSession.beginTransaction();
WebApplicationContext cxt =
WebApplicationContextUtils.getWebApplicationContext( getServletContext());
AnnotationSessionFactoryBean factory = (AnnotationSessionFactoryBean) cxt.getBean( "&sessionFactory");
Iterator iter = factory.getConfiguration().getClassMappings();
while( iter.hasNext()) {
RootClass clz = (RootClass) iter.next();
buildClassIndex( fullTextSession, clz.getMappedClass());
}
tx.commit(); //index are written at commit time
}
然后再每个类的对象都找出来build一下:
private void buildClassIndex(FullTextSession fullTextSession, Class mappedClass) {
//Scrollable results will avoid loading too many objects in memory
fullTextSession.purgeAll( mappedClass);
ScrollableResults results = fullTextSession.createCriteria( mappedClass)
.setFetchSize(BATCH_SIZE).scroll( ScrollMode.FORWARD_ONLY );
int index = 0;
while( results.next() ) {
index++;
fullTextSession.index( results.get(0) ); //index each element
if (index % BATCH_SIZE == 0) {
fullTextSession.flush(); //apply changes to indexes
fullTextSession.clear(); //clear since the queue is processed
}
}
}
很复杂吧。现在简单多了,两行代码:
public void reindex() {
FullTextSession fullTextSession = Search.getFullTextSession( getSession());
fullTextSession.createIndexer().startAndWait();
}
还可以用异步的方式来进行重建索引,直接调用 fullTextSession.createIndexer().start(); 就可以了。
真是三天不学习,赶不上比安奇。