1 package org.terracotta.modules.lucene_2_0_0; 2 3 import java.io.BufferedInputStream ; 4 import java.io.File ; 5 import java.io.FileInputStream ; 6 import java.io.IOException ; 7 8 import org.apache.lucene.analysis.Analyzer; 9 import org.apache.lucene.analysis.standard.StandardAnalyzer; 10 import org.apache.lucene.demo.IndexHTML; 11 import org.apache.lucene.document.Document; 12 import org.apache.lucene.document.Field; 13 import org.apache.lucene.index.IndexWriter; 14 import org.apache.lucene.queryParser.ParseException; 15 import org.apache.lucene.queryParser.QueryParser; 16 import org.apache.lucene.search.Hits; 17 import org.apache.lucene.search.IndexSearcher; 18 import org.apache.lucene.search.Query; 19 import org.apache.lucene.search.Searcher; 20 import org.apache.lucene.store.RAMDirectory; 21 22 import com.tc.util.ZipBuilder; 23 24 public final class LuceneSampleDataIndex { 25 26 public static final String FIELD_PATH = "path"; 27 public static final String FIELD_SUMMARY = "summary"; 28 public static final String FIELD_TITLE = "title"; 29 private static final String HTML_DATA = "sample-html-data-1.0.zip"; 30 private static final String DATA_DIR = "bible"; 31 private final String indexPath; 32 private final RAMDirectory directory; 33 34 public LuceneSampleDataIndex(File workingDir) throws IOException { 35 this.indexPath = workingDir + File.separator + DATA_DIR; 36 if (!new File (indexPath).exists()) { 37 String dataPath = LuceneSampleDataIndex.class.getResource(HTML_DATA).getPath(); 38 BufferedInputStream in = new BufferedInputStream (new FileInputStream (dataPath)); 39 ZipBuilder.unzip(in, workingDir); 40 String [] args = new String [] { "-create", "-index", indexPath, workingDir.getAbsolutePath() }; 41 IndexHTML.main(args); 42 } 43 directory = new RAMDirectory(indexPath); 44 } 45 46 public RAMDirectory publishDirectory() { 48 return directory; 49 } 50 51 public Hits query(String queryString) throws IOException , ParseException { 52 synchronized (directory) { 53 Searcher searcher = new IndexSearcher(directory); 54 Analyzer analyzer = new StandardAnalyzer(); 55 QueryParser parser = new QueryParser("contents", analyzer); 56 Query query = parser.parse(queryString); 57 return searcher.search(query); 58 } 59 } 60 61 public void put(String field, String value) throws Exception { 62 Document doc = new Document(); 63 doc.add(new Field(field, value, Field.Store.YES, Field.Index.TOKENIZED)); 64 synchronized (directory) { 65 final IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(), (directory.list().length == 0)); 66 writer.addDocument(doc); 67 writer.close(); 68 writer.optimize(); 69 } 70 } 71 } 72 | Popular Tags |