2013-03-08 92 views
0

如何索引特定文件夾中的所有文檔文件? 假設我有mydocuments文件夾,其中包含docdocx文件。我需要索引該文件夾中的所有文件以進行高效搜索。你可以建議爲doc文件建立索引文件夾嗎? 注意:我查找了獅身人面像,但它似乎只索引xml和mssql。索引文件夾中的文件

+0

您使用的是哪個版本的solr?你看過https://wiki.apache.org/solr/ExtractingRequestHandler還是SolrCell?有了它們,您可以索引doc文件。 – jpee 2013-03-08 19:40:50

回答

1

我的回答適用於Lucene。

Lucene不「直接」提供了一個API來索引文件或文件夾的內容。我們要做的是

  • 解析文件。您可以使用支持解析各種文件的Apache Tika
  • 用該信息填充Lucene Document對象。
  • 將該文檔傳遞給IndexWriter.addDocument()
  • 對每個文件(即索引中的每個不同條目)重複上述步驟。

直接索引的問題即使存在,也會損失字段創建的靈活性以及選擇特定文檔中該字段的內容。

下面是一個很好的教程,你可以找到示例代碼:Lucene in 5 minutes

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


} 
+1

而不是隻發佈代碼,嘗試至少包括一個解釋的句子。這意味着不僅僅是對OP的參考,而且也是針對同樣問題來到這裏的其他人的參考。沒有解釋它可以幫助更少的人。謝謝! – Jason 2013-03-08 20:38:06

+2

@Jason感謝您的評論。我已經做到了。 – ameertawfik 2013-03-09 05:29:16

相關問題