/* * Created on Jun 19, 2003 * * @author Jeff Linwood, jeff@greenninja.com * */ package com.greenninja.lucene; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; public class Indexer { protected IndexWriter writer = null; protected Analyzer analyzer = new StandardAnalyzer(); public void init(String indexPath) throws IOException { //create a new index every time this is run writer = new IndexWriter(indexPath, analyzer, true); } public void buildIndex() throws IOException { //get the products from the DAO ProductDAO dao = new ProductDAO(); dao.init(); Collection products = dao.getAllProducts(); Iterator iter = products.iterator(); while (iter.hasNext()) { Product product = (Product) iter.next(); // convert the product to a document. Document doc = new Document(); // create an unindexed, untokenized, stored field for the product id doc.add(Field.UnIndexed("productId",product.getId())); // create an indexed, untokenized, stored field for the name doc.add(Field.Keyword("name",product.getName())); // create an indexed, untokenized, stored field for the short description doc.add(Field.Keyword("short",product.getShortDescription())); // create an indexed, tokenized, unstored field for all of the content String content = product.getName() + " " + product.getShortDescription() + " " + product.getLongDescription(); doc.add(Field.Text("content",content)); // add the document to the index try { writer.addDocument(doc); System.out.println("Document " + product.getName() + " added to index."); } catch (IOException e) { System.out.println("Error adding document: " + e.getMessage()); } } //optimize the index writer.optimize(); //close the index writer.close(); } } |