首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

lucene入门范例一(写索引)

2012-11-19 
lucene入门实例一(写索引)copy一个 lucene in action 的入门实例代码:???import java.io.Fileimport java

lucene入门实例一(写索引)

copy一个 lucene in action 的入门实例代码:

?

?

?

import java.io.File;import java.io.FileFilter;import java.io.FileReader;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.document.FieldSelectorResult;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;public class Index {public static void main(String[] args) throws Exception {String indexDir = "F:\\workspace\\JavaDemo\\src\\com\\s\\lucene\\index";//存储lucene索引的文件夹String dataDir = "F:\\workspace\\JavaDemo\\src\\com\\s\\lucene";//lucene源文件long start = System.currentTimeMillis();Index indexer = new Index(indexDir);//初始化indexWriterint numIndexed;try{numIndexed = indexer.index(dataDir, new TextFilesFilter());//创建索引}finally{indexer.close();}long end = System.currentTimeMillis();System.out.println(end-start);}private IndexWriter writer;public Index(String indexDir) throws IOException{Directory dir = FSDirectory.open(new File(indexDir));//创建索引文件夹//创建索引writer 也可以根据IndexWriterConfig创建writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED);}public void close() throws IOException{writer.close();}public int index(String dataDir,FileFilter filter) throws Exception{File[] files = new File(dataDir).listFiles();//列出源文件for (File f : files) {if(!f.isDirectory() && filter.accept(f)){indexFile(f);//遍历源文件,创建索引}}return writer.numDocs();}public static class TextFilesFilter implements FileFilter{public boolean accept(File path){return path.getName().toLowerCase().endsWith(".txt");}}protected Document getDocument(File f) throws Exception{Document doc = new Document();doc.add(new Field("contents",new FileReader(f)));//内容doc.add(new Field("filename",f.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));//文件名doc.add(new Field("fullpath",f.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED)); //文件全路径return doc;}private void indexFile(File f) throws Exception{Document doc = getDocument(f);//创建documentwriter.addDocument(doc);//添加document到索引}}

热点排行