使用Lucene的IndexReader读取索引文件的信息

/*前面学习了创建索引的方法是IndexWriter,这里所使用的是读取所创建的
 * 索引的方法IndexReader.
 * 和他的子类
 * MultiReader
 * */
package indexReader;


import java.io.IOException;


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.MultiReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;


public class IndexReader{


private String INDEX_STORE_PATH = "E:\\Lucene项目\\目标文件";
IndexWriter writer = null;
org.apache.lucene.index.IndexReader reader =  null;
public IndexReader(){
try{
//创建索引

writer = new IndexWriter(INDEX_STORE_PATH, new StandardAnalyzer(), true);

writer.setUseCompoundFile(false);
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();

Field f1 = new Field("bookname", "钢铁是怎样炼成的", Field.Store.YES, Field.Index.TOKENIZED);
Field f2 = new Field("bookname", "英雄儿女", Field.Store.YES, Field.Index.TOKENIZED);
Field f3 = new Field("bookname", "篱笆女人和狗", Field.Store.YES, Field.Index.TOKENIZED);
doc1.add(f1);
doc2.add(f2);
doc3.add(f3);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
writer.close();

//使用IndexReader读取索引
reader = MultiReader.open(INDEX_STORE_PATH);

System.out.println("索引文档列表 : ");
for(int i = 0; i < reader.numDocs(); i++){
System.out.println(reader.document(i));
}

//输出当前索引的版本信息
System.out.println("索引版本: " + reader.getVersion());

//输出当前的索引文件的数量
System.out.println("索引的文本数量: "  + reader.numDocs());

//构造一个词条并在索引中查找
System.out.println("============================");
System.out.println("查找词条女---------->开始查找");
Term term1 = new Term("bookname", "女");
TermDocs docs = reader.termDocs(term1);
while(docs.next()){
System.out.println("---------查找中------------");
System.out.println("含有查找的<"+ term1 +">的Document的编号为" + docs.doc());
System.out.println("Term在文档中出现的次数" + docs.freq());
System.out.println("----------------------------");
}
reader.close();


}catch(IOException e){
e.printStackTrace();
}


}


public static void main(String[] args) {
// TODO Auto-generated method stub
IndexReader IR = new IndexReader();


}


}

你可能感兴趣的:(使用Lucene的IndexReader读取索引文件的信息)