有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);
  }
}

共 (2) 个答案

  1. # 2 楼答案

    如果您想在搜索过程中继续使用RAMDirectory(由于性能优势),但又不想每次都从头开始构建索引,可以先使用基于文件系统的目录创建索引,如NIOFSDirectory(如果在windows上,则不要使用)。然后在搜索时,使用构造函数RAMDirectory(Directory dir)打开原始目录的副本