import javax.management.Query;
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.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocCollector;
/*
* 学习笔记之创建Index
*
* Lucene 版本 2.4.0
*/
public class LuceneJE1 {
private String path = "./index";
public void createIndex() throws Exception {
// 相当于打开了一个数据库的连接准备写入数据
// 注意:如果第三个参数为false并且path没有索引文件
// 就会抛出一个IOException
IndexWriter writer = new IndexWriter(path, new StandardAnalyzer(),
true, MaxFieldLength.UNLIMITED);
// 相当于数据库里行的概念,这里创建了3行数据
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();
// Field相当于数据库中列的概念,这里给一行的数据赋值
doc1.add(new Field("id", "1", Field.Store.YES, Field.Index.ANALYZED));
doc1.add(new Field("name", "cobain", Field.Store.YES,
Field.Index.ANALYZED));
doc1.add(new Field("content", "hello", Field.Store.YES,
Field.Index.ANALYZED));
doc2.add(new Field("id", "2", Field.Store.YES, Field.Index.ANALYZED));
doc2.add(new Field("name", "rose", Field.Store.YES,
Field.Index.ANALYZED));
doc2.add(new Field("content", "hi", Field.Store.YES,
Field.Index.ANALYZED));
doc3.add(new Field("id", "3", Field.Store.YES, Field.Index.ANALYZED));
doc3.add(new Field("name", "mike", Field.Store.YES,
Field.Index.ANALYZED));
doc3.add(new Field("content", "how are you", Field.Store.YES,
Field.Index.ANALYZED));
// 相当于把数据写入数据库
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
// 对写入的数据进行优化,比如压缩Document的索引编号
// 不要在服务器繁忙时对海量数据进行优化
// 最好在服务器空闲或负载小的时候进行
writer.optimize();
// 相当与关闭数据库连接
writer.close();
}
/*
* 这里把刚才建立的数据都查出来
*/
public void search() throws Exception {
Searcher searcher = new IndexSearcher(path);
MatchAllDocsQuery query = new MatchAllDocsQuery();
TopDocCollector results = new TopDocCollector(10);
searcher.search(query, results);
ScoreDoc[] docs = results.topDocs().scoreDocs;
for (int i = 0; i < docs.length; i++) {
System.out.println("Document id:" + docs[i].doc);
System.out.println("Document score:" + docs[i].score);
System.out.println("Document:" + searcher.doc(i));
}
}
public static void main(String[] args) throws Exception {
LuceneJE1 je1 = new LuceneJE1();
je1.createIndex();
je1.search();
}
}