Brian's Waste of Time

Thu, 07 Apr 2005

Lucene Components for Spring

Matt and Dion already spilled the beans, so here's the chili: a bunch of stuff to make using Lucene from Spring more convenient:

public void testDemonstration() throws Exception
{
    LuceneTemplate lucene = (LuceneTemplate) beans.getBean("lucene");
    Document one = new Document();
    one.add(Field.Text("name", "Brian McCallister"));

    Document two = new Document();
    two.add(Field.Text("name", "Eric McCallister"));
    lucene.addDocuments(new Document[] {one, two});

    Document[] results = lucene.searchForDocuments(lucene.parseQuery("Eric", "name"));
    assertEquals(1, results.length);
    assertEquals("Eric McCallister", results[0].get("name"));
}

There are other convenience methods, callback handlers for readers, writers, and searchers which managed opening/closing, etc on the LuceneTemplate, and factory beans for direct access to components without going through the template, but that is a nice example. The Spring config used for this test is:

<beans>
    <bean id="directory" class="org.skife.spring.lucene.RAMDirectoryBean"/>

<!-- <bean id="directory" class="org.skife.spring.lucene.FSDirectoryBean"> -->
<!--   <property name="location"><value>/tmp</value></property>            -->
<!-- </bean>                                                               -->

    <bean id="analyzer" class="org.apache.lucene.analysis.standard.StandardAnalyzer"/>

    <bean id="template" class="org.skife.spring.lucene.LuceneTemplate">
        <property name="directory"><ref bean="directory"/></property>
        <property name="analyzer"><ref bean="analyzer"/></property>
    </bean>
</beans>

The fun part is that the components work with Spring transactions (via readers and writers LuceneUtils, which the template uses as well), so that if you index documents inside a transaction, then roll it back, they aren't added. Ditto removing docs, etc. This is awfully handy if you do things like handle document indexing via an interceptor on your DAO ;-)

Haven't figured out where the code will be hosted, yet. There isn't much. I've offered it to the Spring folks, and have had Spring Modules suggested, but haven't thought hard about anything.

So until then, you can grab the jar (only dependencies are Spring and Lucene) and sources from me, and see the API docs. My apologies for not having a source download -- it was developed as part of another project, and the build and sources are all in there (and I'm too lazy to split out a seperate project since I hope to host it somewhere else =). Until it finds a home, I'll keep pushing stuff to the aforementioned links as I make significant changes.

3 writebacks [/src/java] permanent link