public static void createIndex(File file){
Analyzer ikAnalyzer = new IKAnalyzer(true);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, ikAnalyzer);//设置lucene的版本和分词器
LogMergePolicy logMergePolicy = new LogByteSizeMergePolicy();
logMergePolicy.setMergeFactor(50);
logMergePolicy.setUseCompoundFile(true);//启用复合式索引文件格式,合并多个segment
config.setOpenMode(OpenMode.CREATE_OR_APPEND);//设置索引打开模式
Directory directory = null;
IndexWriter indexWriter = null;
try {
directory = FSDirectory.open(new File(getIndexPath()));
indexWriter = new IndexWriter(directory, config);
if(file.isDirectory()){
for (File text : file.listFiles()) {
if(text.isFile()){
indexWriter.addDocument(createDocument(text));
indexWriter.commit();
}
}
}else if(file.isFile()){
indexWriter.addDocument(createDocument(file));
indexWriter.commit();
}
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
private static Document createDocument(File text){
Document doc = new Document();
doc.add(new Field("name", FileHelper.getFilename(text), Store.YES, Index.ANALYZED));
doc.add(new Field("path", text.getAbsolutePath(), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field("content", FileHelper.getContent(text), Store.NO, Index.ANALYZED));
log.debug("fileName :"+FileHelper.getFilename(text));
log.debug( "fileContent :"+FileHelper.getContent(text));
return doc;
}
原文:http://my.oschina.net/u/1778309/blog/392018