Lucene2.0简单例子 luceneApache
程序员文章站
2024-03-18 20:38:16
...
package gt.test.lucene; import java.io.IOException; 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; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; public class Test { /** * @param args * @author Goodtiger */ public static void main(String[] args) { try { Analyzer analyzer = new StandardAnalyzer(); //将索引存在内存中 Directory directory = new RAMDirectory(); //将索引存在磁盘的话,用下面这句 //Directory directory = FSDirectory.getDirectory("/tmp/testindex", true); IndexWriter iwriter = new IndexWriter(directory, analyzer, true); iwriter.setMaxFieldLength(25000); Document doc = new Document(); String text = "This is the text to be indexed."; doc.add(new Field("fieldname", text, Field.Store.YES, Field.Index.TOKENIZED)); iwriter.addDocument(doc); iwriter.close(); IndexSearcher isearcher = new IndexSearcher(directory); // Parse a simple query that searches for "text": QueryParser parser = new QueryParser("fieldname",analyzer); Query query = parser.parse("text"); Hits hits = isearcher.search(query); if(hits.length() == 1) { System.out.println("搜索\"text\""); Document d = hits.doc(0); System.out.println(d.get("fieldname")); }else { System.out.println("没有搜索到结果"); } // 遍历搜索结果: for (int i = 0; i < hits.length(); i++) { Document hitDoc = hits.doc(i); System.out.println(hitDoc.get("fieldname")); } isearcher.close(); directory.close(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }