2、构建索引

索引过程

主要操作步骤:

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;

	@Test
	public 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();
		}
	}
	@Test
	public  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类写入新创建的索引。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值