好的,在lucene indexing
中有这么多疑问之后,我尝试了一个程序来索引文件夹中的每个文件,并能够索引包含大部分ppt,pdf和docs的131 MB文件。索引文件大小约为80 MB。它在36秒内完成,并在7毫秒内搜索了一个查询。
这是我的索引器文件,它实际上来自Lucene
在行动书
package lia.meetlucene;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.FileReader;
public class Indexer {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException("Usage: java " + Indexer.class.getName()
+ " <index dir> <data dir>");
}
String indexDir = args[0]; //1
String dataDir = args[1]; //2
long start = System.currentTimeMillis();
Indexer indexer = new Indexer(indexDir);
int numIndexed;
try {
numIndexed = indexer.index(dataDir);
} finally {
indexer.close();
}
long end = System.currentTimeMillis();
System.out.println("Indexing " + numIndexed + " files took "
+ (end - start) + " milliseconds");
}
private IndexWriter writer;
public Indexer(String indexDir) throws IOException {
Directory dir = FSDirectory.open(new File(indexDir));
writer = new IndexWriter(dir, //3
new StandardAnalyzer( //3
Version.LUCENE_30),//3
true, //3
IndexWriter.MaxFieldLength.UNLIMITED); //3
}
public void close() throws IOException {
writer.close(); //4
}
public int index(String dataDir)
throws Exception {
try{
File[] files = new File(dataDir).listFiles();
for (File f: files) {
if(f.isDirectory())
{
index(f.getAbsolutePath());
}
else if (!f.isDirectory() &&
!f.isHidden() &&
f.exists() &&
f.canRead()
) {
indexFile(f);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
return writer.numDocs(); //5
}
protected Document getDocument(File f) throws Exception {
Document doc = new Document();
doc.add(new Field("contents", new FileReader(f))); //7
doc.add(new Field("filename", f.getName(), //8
Field.Store.YES, Field.Index.NOT_ANALYZED));//8
doc.add(new Field("fullpath", f.getCanonicalPath(), //9
Field.Store.YES, Field.Index.NOT_ANALYZED));//9
return doc;
}
private void indexFile(File f) throws Exception {
System.out.println("Indexing " + f.getCanonicalPath());
Document doc = getDocument(f);
writer.addDocument(doc); //10
}
}
答案 0 :(得分:0)
关于您的代码的几条评论:
doc.add(new Field("contents", new FileReader(f))); //7
你确定这是对的吗?如果你的文件是二进制文件(ppt,pdf ...),你在这里索引原始字节,你应该看一下文本提取工具,如tika
这会大大减小你索引的大小。
同时验证您的索引是否使用compound file format,这会使其变小。