lucece建立索引过程

 

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
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;


public class TextFileIndexer {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO 自动生成方法存根
		File fileDir=new File("D:\\chenzk\\lucene");
		Analyzer luceneAnalyzer=new StandardAnalyzer();
		//创建一个类StandardAnalyzer的一个实例,这个实例是从文本中提取索引项的
		File   indexDir = new File("C:\\luceneIndex");

		IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
        //第一个参数是存储索引文件的路径,第二个参数是指定了在索引的过程中使用什么样的分词器,最后一个参数是一个布尔的参数如果
		//为真表示要创建一个新的索引,如果值为假表示打开一个已经存在的索引
		File [] textFiles=fileDir.listFiles();
		long startTime=new Date().getTime();
		
		//add documents to the index
		for(int i=0;i<textFiles.length;i++)
		{
			if(textFiles[i].isFile()&&textFiles[i].getName().endsWith(".txt"))
			{ //只要你能将要索引的文件转化成文本格式lucene就能为你的文档建立索引
				System.out.println("File "+textFiles[i].getCanonicalPath()+"  is being indexed");
				Reader textReader=new FileReader(textFiles[i]);
				
				//以下是如何添加一个文档到索引文件中
			    Document document=new Document();//	它是由一个或者多个Field组成,我们可以把它想象是一个实际文档
			    //实际的Field是实际文档一些属性,
			    document.add(Field.Text("content",textReader));//域的名称我们需要索引的文本文件的内容
			    document.add(Field.Text("path", textFiles[i].getPath()));//我们需要索引的文本文件的路径
			    indexWriter.addDocument(document);
			    
			    
			}
		}
		
		indexWriter.optimize();
		indexWriter.close();//当我们把文档添加到索引中后,不要忘记关闭索引,这样才保证Lucene把添加的文档写回到硬盘上。
		long endTime=new Date().getTime();
		
		
		
		System.out.println("It took "+(endTime-startTime)+" millseconds to create an index for the files in the directory "+fileDir.getPath()) ;
	}

}

 

 

 

 

 

File D:\chenzk\lucene\1.txt  is being indexed
File D:\chenzk\lucene\2.txt  is being indexed
File D:\chenzk\lucene\3.txt  is being indexed
File D:\chenzk\lucene\segments.txt  is being indexed
It took 187 millseconds to create an index for the files in the directory D:\chenzk\lucene

 

请大家提供宝贵的意见!谢谢

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值