標籤:建立索引 執行 項目 exce bst new ddd 成員變數 遍曆
時間:
2015/3/18
楊鑫newlife
對於文檔的預先處理後。就要開始使用Lucene來處理相關的內容了。
這裡使用的Lucene的過程例如以下:
首先要為處理對象機那裡索引
二是構建查詢對象
三是在索引中尋找
這裡的代碼是處理建立索引的部分
代碼:
package ch2.lucenedemo.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import jeasy.analysis.MMAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.index.IndexWriter;
public class IndexProcessor {
//成員變數。儲存建立的索引檔案存放的位置
private String INDEX_STORE_PATH = "E:\\Lucene項目\\索引檔案夾";
//建立索引
public void createIndex(String inputDir){
try
{
System.out.println("程式開始執行。正在建立索引->->->->->");
IndexWriter writer = new IndexWriter(INDEX_STORE_PATH, new MMAnalyzer(), true);
File filesDir = new File(inputDir);
//取得全部須要建立索引的檔案數組
File[] files = filesDir.listFiles();
//遍曆數組
for(int i = 0; i < files.length; i++){
//擷取檔案名稱
String fileName = files[i].getName();
//推斷檔案是否為txt類型的檔案
if(fileName.substring(fileName.lastIndexOf(".")).equals(".txt")){
//建立一個新的Document
Document doc = new Document();
System.out.println("正在為檔案名稱建立索引->->->->");
//為檔案名稱建立一個Field
Field field = new Field("filename", files[i].getName(), Field.Store.YES, Field.Index.TOKENIZED);
doc.add(field);
System.out.println("正在為檔案內容建立索引->->->->");
//為檔案內容建立一個Field
field = new Field("content", loadFileToString(files[i]), Field.Store.NO, Field.Index.TOKENIZED);
doc.add(field);
//把Document增加到IndexWriter
writer.addDocument(doc);
}
}
writer.close();
System.out.println("程式建立結束->->->->");
}catch(Exception e){
e.printStackTrace();
}
}
/*
* 從檔案裡把內容讀取出來,全部的內容就放在一個String中返回
* */
public String loadFileToString(File file){
try{
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String line= br.readLine();
while(line != null){
sb.append(line);
line = br.readLine();
}
br.close();
return sb.toString();
}catch(IOException e){
e.printStackTrace();
return null;
}
}
public static void main(String[] args){
IndexProcessor ip = new IndexProcessor();
ip.createIndex("E:\\Lucene項目\\目標檔案");
}
}
使用Lucene對預先處理後的文檔進行建立索引(可執行)