如何持久保存Lucene文档索引,以便每次程序启动时都不需要将文档加载到文档中?

Swe*_*man 1 java lucene

我正在尝试设置Lucene来处理存储在数据库中的一些文档.我从这个HelloWorld示例开始.但是,创建的索引不会保存在任何位置,每次运行程序时都需要重新创建.有没有办法保存Lucene创建的索引,以便每次程序启动时都不需要将文档加载到它中?

public class HelloLucene {
  public static void main(String[] args) throws IOException, ParseException {
    // 0. Specify the analyzer for tokenizing text.
    //    The same analyzer should be used for indexing and searching
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);

    // 1. create the index
    Directory index = new RAMDirectory();

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

    IndexWriter w = new IndexWriter(index, config);
    addDoc(w, "Lucene in Action");
    addDoc(w, "Lucene for Dummies");
    addDoc(w, "Managing Gigabytes");
    addDoc(w, "The Art of Computer Science");
    w.close();

    // 2. query
    String querystr = args.length > 0 ? args[0] : "lucene";

    // the "title" arg specifies the default field to use
    // when no field is explicitly specified in the query.
    Query q = new QueryParser(Version.LUCENE_35, "title", analyzer).parse(querystr);

    // 3. search
    int hitsPerPage = 10;
    IndexReader reader = IndexReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
    searcher.search(q, collector);
    ScoreDoc[] hits = collector.topDocs().scoreDocs;

    // 4. display results
    System.out.println("Found " + hits.length + " hits.");
    for(int i=0;i<hits.length;++i) {
      int docId = hits[i].doc;
      Document d = searcher.doc(docId);
      System.out.println((i + 1) + ". " + d.get("title"));
    }

    // searcher can only be closed when there
    // is no need to access the documents any more. 
    searcher.close();
  }

  private static void addDoc(IndexWriter w, String value) throws IOException {
    Document doc = new Document();
    doc.add(new Field("title", value, Field.Store.YES, Field.Index.ANALYZED));
    w.addDocument(doc);
  }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 5

您正在 RAM 中创建索引:

Directory index = new RAMDirectory();
Run Code Online (Sandbox Code Playgroud)

http://lucene.apache.org/java/3_0_1/api/core/org/apache/lucene/store/RAMDirectory.html

IIRC,您只需将其切换到基于文件系统的目录实现之一。 http://lucene.apache.org/java/3_0_1/api/core/org/apache/lucene/store/Directory.html


pm_*_*abs 5

如果您希望在搜索期间继续使用RAMDirectory(由于性能优势)但不希望每次都从头开始构建索引,您可以首先使用基于文件系统的目录(如NIOFSDirectory)创建索引(不要使用if你在窗户上).然后来搜索时间,使用构造函数RAMDirectory(目录目录)打开原始目录的副本.