如何填充lucene 5.3索引

时间:2015-12-08 15:14:47

标签: lucene

我编写了以下类来填充Lucene索引。我想为Lucene构建一个索引,以便我可以查询特定文档。不幸的是,我的文档没有添加到索引中。

这是我的代码:

public class LuceneIndexer {
private IndexWriter indexWriter;
private IndexReader indexReader;

    public LuceneIndexer() throws Exception {
        Directory indexDir = FSDirectory.open(Paths.get("./index-directory"));
        IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());
        config.setCommitOnClose(true);
        config.setOpenMode(OpenMode.CREATE);

        this.indexWriter = new IndexWriter(indexDir, config);
        indexReader = DirectoryReader.open(this.indexWriter, true);
}

    public void indexRelation(String subject, String description, String object) throws IOException {
    System.out.println("Indexing relation between: " + subject+" and "+object);

    Document doc = new Document();
    doc.add(new TextField("subject", subject, Field.Store.YES));
    doc.add(new TextField("description", description, Field.Store.YES));
    doc.add(new TextField("object", object, Field.Store.YES));

    indexWriter.addDocument(doc);
}

public void commit() throws Exception {
        indexWriter.commit();
}

public int getNumberOfRelations() {
    return indexReader.numDocs();
}
}

我试图让以下测试用例通过:

public class LuceneIndexerTest {
private LuceneIndexer instance;

@Before
public void setUp() throws SQLException, IOException {
    instance = new LuceneIndexer();
    instance.indexRelation("subject1","descr1","object1");
    instance.indexRelation("subject2","descr2","object2");
    instance.indexRelation("subject3","descr3","object3");
    instance.commit();
}

@After
public void tearDown() throws IOException {
    instance.close();
}

@Test
public void testIndexing() {
    Assert.assertEquals(3, instance.getNumberOfRelations());
    Assert.assertEquals(3, instance.getNumberOfRelations("subject"));
}

不幸的是,Testcase说索引中有0个文档。

1 个答案:

答案 0 :(得分:1)

来自Lucene's javadoc"在打开新的IndexReader" 之前,通过IndexWriter对索引所做的任何更改都不会显示。

indexReader在创建IndexReader对象时保留索引的视图。只需在每次提交后创建一个新的,并且indexReader将按预期工作。

以下是LuceneIndexer类的修复:

public void commit() throws Exception {
    indexWriter.commit();
    if (indexReader != null)
        indexReader.close();
    indexReader = DirectoryReader.open(this.indexWriter, true);
}