2、构建索引

来源:互联网 发布:obs直播软件 清晰度 编辑:程序博客网 时间:2024/06/06 04:47

索引过程

主要操作步骤:

1、将原始文档转换成文本

2、分析文本

3、将分析好的文本保存至索引中


基本索引demo

 package com.lucene;import java.io.IOException;import org.apache.lucene.analysis.WhitespaceAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import org.junit.Test;public class IndexingTest {private Directory directory;private IndexWriter writer;@Testpublic void creasteIndex() throws  Exception {directory = new RAMDirectory();try {writer = getWriter();Document doc = new Document();doc.add(new Field("str", "hello,Wrold!", Field.Store.YES,Field.Index.ANALYZED));writer.addDocument(doc);} catch (IOException e) {e.printStackTrace();}finally{writer.close();}}@Testpublic  void IndexReader() throws Exception{creasteIndex();IndexReader reader=IndexReader.open(directory);System.out.println("文档数:"+reader.maxDoc());reader.clone();}@SuppressWarnings("deprecation")private IndexWriter getWriter() throws IOException {return new IndexWriter(directory, new WhitespaceAnalyzer(),IndexWriter.MaxFieldLength.UNLIMITED);}}

说明

1、建立新的RAMDirectory对象用来存放索引。
2、在Directory对象上创建IndexWriter对象。
3、创建 Document对象和Fields对象,然后将Document对象加入索引。
IndexWriter三个变量说明: 
1、Directory类,索引对象储存于该类。
2、分析器,被用来索引语汇单元化的域。
3、MaxFieldLength.UNLIMITED,该变量是必要的,它指示IndexWriter索引文档中所有的语汇单元。
NOTE  
IndexWriter类初始化方法并不显示包含索引是否已创建的布尔型,它在初始化时会首先检查传入的Directory类是否已包含索引。如果索引存在,IndexWriter类则在该索引上追加内容,否则后者将向Directory类写入新创建的索引。