【问题标题】:How to creat index and search query in Java Lucene 6.2.0如何在 Java Lucene 6.2.0 中创建索引和搜索查询
【发布时间】:2016-09-22 09:20:58
【问题描述】:

我想使用 Lucene 6.2.0 版本,我在 java 中创建了两个函数 creatIndex 和 searchIndex 但它没有运行。我不明白如何使用 Field 来参数 Documents 方法。

public void searchIndex(String sentence) throws IOException
{
    File dir = new File(INDEX_DIRECTORY);
    Path path = dir.toPath();
    Directory directory = FSDirectory.open(path);
    DirectoryReader ireader=DirectoryReader.open(directory);
    IndexSearcher isearcher=new IndexSearcher(ireader);
    PhraseQuery.Builder builder = new PhraseQuery.Builder(); 
    String[] words = sentence.split(" ");
    for (String word : words) {
        builder.add(new Term("contents", word));
    }
    PhraseQuery pq = builder.build();
    TopDocs topDocs = isearcher.search(pq, 10);
    for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
        Document doc = isearcher.doc(scoreDoc.doc);
        System.out.println(doc);
    }
}

【问题讨论】:

  • 它没有运行,这是错误:在 study_lucense.Study_Lucense.creatDocument(Study_Lucense.java:55) 的 org.apache.lucene.document.Field.(Field.java:249)在 study_lucense.Study_Lucense.main(Study_Lucense.java:86)
  • 如果您在问题中添加错误(包括抛出的异常类型,而不是作为注释)会更有帮助。问题底部应该有一个“编辑”链接,您可以将其添加进去。

标签: java lucene information-retrieval


【解决方案1】:

我遇到了三个问题:

  1. 您的creatDocumentsFiles 参数处寻找要索引的文件的同一位置打开一个索引。然后,您的 searchIndex 方法将在 INDEX_DIRECTORY 处查找索引。我认为您的creatDocuments 也应该在INDEX_DIRECTORY 开设作家。喜欢

    FSDirectory luceneDirectory = FSDirectory.open(new File(INDEX_DIRECTORY).toPath());
    IndexWriterConfig conf = new IndexWriterConfig();
    try (IndexWriter indexWriter = new IndexWriter(directory, conf)) {
        for (File file : new File(Files).listFiles()) {
        ...
    
  2. 您的FieldType 将无法使用。您需要至少指定它被索引或存储。我建议您不要从自定义字段类型开始。只需使用带有预定义字段类型的Field 实现,例如TextField(请参阅Field documentation 中的“直接已知子类”列表)。

        Field contentField = new TextField(LuceneConstants.CONTENTS, reader);
        Field fileNameField = new TextField(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES);
        Field filePathField = new TextField(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.NO);
    
  3. 您正在重复使用相同的Document,而不是为每个文件创建一个新的。您应该为 for 循环的每次迭代构建一个新的 Document

【讨论】:

  • 2 。如果我不使用 FieldType ,那就是错误。我正在使用 Lucene 版本 6.2.0 。它不适用于 Field 构造函数。
  • @drag - 这就是我推荐使用TextField 的原因。如果你使用Field,那么是的,你需要生成一个FieldType,明确指定字段的索引方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多