java - 如何持久化Lucene文档索引,不需要每次程序启动时都加载文档?

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

最佳答案

您正在 RAM 中创建索引:

Directory index = new RAMDirectory();

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

关于java - 如何持久化Lucene文档索引,不需要每次程序启动时都加载文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146604/

相关文章:

java - 我将如何在java中执行这个命令?

java - 如何使用 Spring Boot 修改 Wildfly/JBoss 配置

Java,找不到符号: method methodName(org. bla.blabla.myClass)

java - jvm崩溃后如何清除lucene write.lock文件的锁定?

java - 将 pdf 转换为代码的库

java - Android Intent 选择设置默认应用

java - 将版权 header 添加到所有项目文件(.java、.xml、...)

performance - ElasticSearch 和突出显示性能 - 普通与快速矢量突出显示

java - 如何在 Lucene 中实现数百万条记录的正确分页

search - Lucene 编号提取