Lucene初使用
其中用到的几个jar包
相关代码如下:
复制代码
package com.eplant;
import java.io.IOException;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
/*
* @author Knight_Key
*/
public class ReadWrite {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// 创建一个内存目录对象
RAMDirectory directory = new RAMDirectory();
///创建索引写入对象
IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(),true, IndexWriter.MaxFieldLength.UNLIMITED);
// 创建Document 文档对象
Document doc = new Document();
doc.add(new Field("name", "wangxiaowu", Field.Store.YES,Field.Index.ANALYZED));
writer.addDocument(doc);
writer.close(); // 这里关闭
IndexSearcher searcher = new IndexSearcher(directory);
// 搜索关键字
Query query = new TermQuery(new Term("name", "lucene"));
// 去索引目录中查询
TopDocs rs = searcher.search(query, null, 10);
for (int i = 0; i < rs.scoreDocs.length; i++) {
Document firstHit = searcher.doc(rs.scoreDocs[i].doc);
System.out.println("name:" + firstHit.getField("name").stringValue());
}
writer.close();
directory.close();
}
}