Sunday, December 20, 2009

Hibernate Search + Apache Lucene (tricks)

In this post I would like to show a few Hibernate Search tricks which could be useful in some cases (at least, I use them quite often):

  • how to get all indexed properties for entity?
  • final Class< ? > entityClass = ...;

    final FullTextSession fullTextSession = Search.getFullTextSession(
    sessionFactory.getCurrentSession() );

    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    final ReaderProvider readerProvider = searchFactory.getReaderProvider();

    final Collection< String > names = new ArrayList< String >();
    IndexReader indexReader = null;

    try {
    indexReader = readerProvider.openReader( searchFactory.getDirectoryProviders( clazz ) );
    for( Object obj: indexReader.getFieldNames( FieldOption.INDEXED ) ) {
    if( obj instanceof String ) {
    String name = ( String )obj;
    names.add( name );
    }
    }
    } finally {
    if( indexReader != null ) {
    readerProvider.closeReader( indexReader );
    }
    }
  • how to reindex whole existing database?
  • final FullTextSession fullTextSession = Search.getFullTextSession(
    sessionFactory.getCurrentSession() );

    final Set< ? > entitites = new HashSet< ? >();
    // Get all indexed persistent entities from Hibernate session factory
    Iterator< ? > iterator = sessionFactory.getConfiguration().getClassMappings();
    while( iterator.hasNext() ) {
    Object obj = iterator.next();
    if( obj instanceof PersistentClass ) {
    PersistentClass persistentClass = ( PersistentClass )obj;
    try {
    Class< ? > clazz = Class.forName( persistentClass.getClassName() );
    if( clazz.getAnnotation( Indexed.class ) != null ) {
    entitites.add( clazz );
    }
    }
    } catch( ClassNotFoundException ex ) {
    ex.printStackTrace();
    }
    }

    for( Class< ? > entityClass: entitites ) {
    fullTextSession.purgeAll( entityClass );
    fullTextSession.flushToIndexes();

    for( Object entity: session.createCriteria( entityClass ).list() ) {
    fullTextSession.index( entity );
    }
    }

    fullTextSession.flushToIndexes();
    fullTextSession.getSearchFactory().optimize();

No comments: