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 indexfor(int i=0;i<textFiles.length;i++){if(textFiles.isFile()&&textFiles.getName().endsWith(".txt")){ //只要你能将要索引的文件转化成文本格式lucene就能为你的文档建立索引System.out.println("File "+textFiles.getCanonicalPath()+"is being indexed");Reader textReader=new FileReader(textFiles);//以下是如何添加一个文档到索引文件中 Document document=new Document();//它是由一个或者多个Field组成,我们可以把它想象是一个实际文档 //实际的Field是实际文档一些属性, document.add(Field.Text("content",textReader));//域的名称我们需要索引的文本文件的内容 document.add(Field.Text("path", textFiles.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.txtis being indexedFile D:\chenzk\lucene\2.txtis being indexedFile D:\chenzk\lucene\3.txtis being indexedFile D:\chenzk\lucene\segments.txtis being indexedIt took 187 millseconds to create an index for the files in the directory D:\chenzk\lucene
请大家提供宝贵的意见!谢谢
页:
[1]