The BitWorm SEO Blog

December 11, 2007

Multi-Field Lucene Example

Filed under: Lucene — Tags: , — admin @ 11:37 am

Storing and search more than one field is very easy to do in Lucene — This can make your lucene search engine much more powerful!

Tip: If you’re not already familiar with how to index and search single field documents, this is intended to build on our Simple Lucene Example.

Lucene Example Code: Multi-Field Documents

Create a Lucene document with more than one field

   String content = "This is the example text I want to have Lucene index";

   Document doc = new Document();

   doc.add(Field.Keyword("keyword","Java"));

   doc.add(Field.Text("title","My Document Title"));

   doc.add(Field.Text("content",content));

You would then add the document to the index like normal.

Create a Lucene MultiFieldQueryParser

   String fields[] = {"keyword","title","content"};

   String queryString = "Java";

   try {

 Query query =  MultiFieldQueryParser.parse(queryString,fields,new StandardAnalyzer());

   } catch (ParseException e) {

 System.out.println("Lucene ParseException: " + e. getMessage);

 e.printStackTrace();

   }

Read the additional fields from the returned hits

   int hitCount = hits.length();

   for(int i=0; (i < hitCount && i < 10); i++){

 Document doc = hits.doc(i);

 System.out.println(doc.get("keyword") + ", " + doc.get("title") + ", " + doc.get("content"));

   }

That’s it!

That all you need to do to take the step to multi-field Lucene documents and searching from a single field.

1 Comment »

  1. Thanks you so much. It is really helpful article and I wanted this to search for an item that may exist multiple colums in a database. One improper approach here is, it requires to provide multiple or copy of keywords for all colums to be searched in it. Like this:
    String fields[] = {”color”,”details”};
    String keywords[] = {”white”,”white”};

    This could have been made to provide single keyword over multiple fields, but unfortunately it is not possible. Anyway its ok and serves better :)

    Thank you!

    - Veeresh

    Comment by Veeresh — May 13, 2009 @ 5:40 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress