01: package org.terracotta.modules.lucene_2_0_0;
02:
03: import java.io.BufferedInputStream;
04: import java.io.File;
05: import java.io.FileInputStream;
06: import java.io.IOException;
07:
08: import org.apache.lucene.analysis.Analyzer;
09: 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: private static final String HTML_DATA = "sample-html-data-1.0.zip";
27: private static final String DATA_DIR = "bible";
28:
29: private final String indexPath;
30: private final RAMDirectory directory;
31:
32: public LuceneSampleDataIndex(File workingDir) throws IOException {
33: this .indexPath = workingDir + File.separator + DATA_DIR;
34: if (!new File(indexPath).exists()) {
35: String dataPath = LuceneSampleDataIndex.class.getResource(
36: HTML_DATA).getPath();
37: BufferedInputStream in = new BufferedInputStream(
38: new FileInputStream(dataPath));
39: ZipBuilder.unzip(in, workingDir);
40: String[] args = new String[] { "-create", "-index",
41: indexPath, workingDir.getAbsolutePath() };
42: IndexHTML.main(args);
43: }
44: directory = new RAMDirectory(indexPath);
45: }
46:
47: public Hits query(String queryString) throws IOException,
48: ParseException {
49: Searcher searcher = new IndexSearcher(directory);
50: Analyzer analyzer = new StandardAnalyzer();
51: QueryParser parser = new QueryParser("contents", analyzer);
52: Query query = parser.parse(queryString);
53: return searcher.search(query);
54: }
55:
56: public void put(String field, String value) throws Exception {
57: Document doc = new Document();
58: doc.add(new Field(field, value, Field.Store.YES,
59: Field.Index.TOKENIZED));
60: final IndexWriter writer = new IndexWriter(directory,
61: new StandardAnalyzer(), (directory.list().length == 0));
62: writer.addDocument(doc);
63: writer.optimize();
64: writer.close();
65: }
66: }
|