Apache Lucene: 如何将索引保存到文件中?

6
我正在开发一款应用程序,可以对一个很大的静态数据仓库进行索引搜索。这不是一个服务器-客户端应用程序,在该应用程序中,服务器始终处于运行状态,而是一种本地应用程序,每次只在需求时启动。
我希望能够对存储库中的文件进行一次索引,并将我的工作保存到文件中。然后,我希望我的应用程序的每个用户都能够从已保存的文件中加载已创建的索引。
我看到了“Lucene in 5 Minutes”中的以下基本代码:
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
Directory index = new RAMDirectory();

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);

IndexWriter w = new IndexWriter(index, config);
addDoc(w, "Lucene in Action", "193398817");
addDoc(w, "Lucene for Dummies", "55320055Z");
addDoc(w, "Managing Gigabytes", "55063554A");
addDoc(w, "The Art of Computer Science", "9900333X");
w.close();


private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
    Document doc = new Document();
    doc.add(new TextField("title", title, Field.Store.YES));
    doc.add(new StringField("isbn", isbn, Field.Store.YES));
    w.addDocument(doc);
}
  • 我现在怎样才能将变量analyzer,indexconfig保存到文件中呢?
  • 我以后怎样才能从保存的文件中加载它们,并用于查询?
1个回答

5

我有一个解决方案 - 我将在这里与您分享:

应该采取的整个更改是,不再使用 RAMDirectory 索引,而是使用 FSDirectory

示例:

FSDirectory index = FSDirectory.open(Paths.get("C:\\temp\\index.lucene"));

在���面的例子中,将创建目录C:\temp\index.lucene并将索引写入其中。
现在我可以按照“Lucene in 5 Minutes”中显示的步骤查询索引:http://www.lucenetutorial.com/lucene-in-5-minutes.html 因此,如果我想在另一个应用程序中运行查询,只需以同样的方式打开索引,就可以立即对其进行查询... 不需要重新对文档建立索引...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接