我需要定期刷新索引。这意味着 索引将随着文档的添加而定期更新 你认为这是解决方案吗?我需要一个示例源代码 能够刷新索引。
好的就像下面的源代码一样。
public class SimpleFileIndexer {
public static void main(String[] args) throws Exception {
File indexDir = new File("C:/Users/Raden/Documents/lucene/LuceneHibernate/adi");
File dataDir = new File("C:/Users/Raden/Documents/lucene/LuceneHibernate/adi");
String suffix = "txt";
SimpleFileIndexer indexer = new SimpleFileIndexer();
int numIndex = indexer.index(indexDir, dataDir, suffix);
System.out.println("Total files indexed " + numIndex);
}
private int index(File indexDir, File dataDir, String suffix) throws Exception {
IndexWriter indexWriter = new IndexWriter(
FSDirectory.open(indexDir),
new SimpleAnalyzer(),
true,
IndexWriter.MaxFieldLength.LIMITED);
indexWriter.setUseCompoundFile(false);
indexDirectory(indexWriter, dataDir, suffix);
int numIndexed = indexWriter.maxDoc();
indexWriter.optimize();
indexWriter.close();
return numIndexed;
}
private void indexDirectory(IndexWriter indexWriter, File dataDir, String suffix) throws IOException {
File[] files = dataDir.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isDirectory()) {
indexDirectory(indexWriter, f, suffix);
}
else {
indexFileWithIndexWriter(indexWriter, f, suffix);
}
}
}
private void indexFileWithIndexWriter(IndexWriter indexWriter, File f, String suffix) throws IOException {
if (f.isHidden() || f.isDirectory() || !f.canRead() || !f.exists()) {
return;
}
if (suffix!=null && !f.getName().endsWith(suffix)) {
return;
}
System.out.println("Indexing file " + f.getCanonicalPath());
Document doc = new Document();
doc.add(new Field("contents", new FileReader(f)));
doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES, Field.Index.ANALYZED));
indexWriter.addDocument(doc);
}
}
上面的源代码可以在给定目录时索引文档 文本文件。现在我要问的是如何让代码运行 持续?我应该用什么课?所以每次都有新的 添加到该目录的文件然后lucene将索引那些 文件自动,你能帮我解决这个问题。我真的 需要知道什么是最好的解决方案。