使用Lucene對預先處理後的文檔進行建立索引(可執行)

來源:互聯網
上載者:User

標籤:建立索引   執行   項目   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對預先處理後的文檔進行建立索引(可執行)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.