0

如何索引特定文件夹中的所有 doc 文件?假设我有mydocuments包含文件docdocx文件夹。我需要索引该文件夹中的所有文件以进行有效搜索。您对doc文件索引文件夹有何建议?注意:我一直在寻找 sphinx,但它似乎只索引 xml 和 mssql。

4

2 回答 2

1

我的回答适用于 Lucene。

Lucene 不“直接”提供 API 来索引文件或文件夹的内容。我们要做的就是

  • 解析文件。您可以使用支持解析大量文件的Apache Tika 。
  • 使用该信息填充Lucene Document对象。
  • 将该文档传递给 IndexWriter.addDocument()
  • 对每个文件重复上述步骤,即索引中的每个不同条目。

直接索引的问题,即使它存在,也失去了在特定文档中创建字段和选择与该字段相关的内容的灵活性。

以下是一个很好的教程,您可以在其中找到示例代码:Lucene in 5 minutes

于 2013-03-08T19:45:06.173 回答
1

我假设您的问题是索引某个文件夹中的文本文件列表。因此,这是索引它们的示例代码。但是,如果您正在索引 word 文档,那么您需要更改 getDocument 方法来解析和填充 Lucene 文档。

关键点是:

  1. 创建一个 IndexWriter。
  2. 使用 dir.listFiles() 方法获取文件夹中的文件列表。
  3. 遍历文件并一次创建一个 Lucene 文档
  4. 将 Lucene 文档添加到索引。
  5. 添加完文档后,提交更改并关闭 indexWriter。

如果您正在寻找从 word 文档或 PDF 文件中解析和读取,那么您需要使用 Apache POIPDFBox库。

请注意,我仅将 RAMDirectory 类用于演示,您需要使用 FSDirectory 代替。

我希望这能解决你的问题。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;


public class IndexFolders {

    public static void main(String[] args) throws FileNotFoundException, IOException{
        String path = args[0];
        File dir = new File(path);

        Directory indexDir = new RAMDirectory();
        Version version = Version.LUCENE_40;
        Analyzer analyzer = new StandardAnalyzer(version);
        IndexWriterConfig config = new IndexWriterConfig(version, analyzer);
        IndexWriter indexWriter = new IndexWriter(indexDir, config);

        for (File file : dir.listFiles()){
            indexWriter.addDocument(getDocument(file));
        }

        indexWriter.commit();
        indexWriter.close();
    }


    public static Document getDocument(File file) throws FileNotFoundException
    {
        Scanner input = new Scanner(file);
        StringBuilder builder = new StringBuilder();

        while(input.hasNext()){
            builder.append(input.nextLine());
        }

        Document document = new Document();
        document.add(new Field("text", builder.toString(),org.apache.lucene.document.TextField.TYPE_STORED));
        return document;
    }


}
于 2013-03-08T20:18:40.257 回答