(http://www.chinaitpower.com/A200507/2005-07-27/170086.html)
作者:未知 時(shí)間:2005-07-27 22:19 出處:CSDN 責編:chinaitpower
摘要:用Lucene建立索引及查詢(xún)示例
首先去 apache 網(wǎng)站下載 lucene 的開(kāi)發(fā)包,并配置好環(huán)境變量
http://jakarta.apache.org/lucene/docs/index.html
建立索引程序:
/*
* Created on 2004-4-26
*/
import org.apache.lucene.index.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.*;
import java.io.*;
/**
* @author bell.wang
*/
public class IndexFiles {
public static void main(String[] args) {
try{
IndexWriter writer = new IndexWriter("myindex", new StandardAnalyzer(), true);
File files = new File("mydoc");
String[] Fnamelist = files.list();
for (int i = 0; i < Fnamelist.length; i++){
File file = new File(files,Fnamelist[i]);
Document doc = new Document();
Field fld = Field.Text("path", file.getPath());
doc.add(fld);
fld = Field.Keyword("modified", DateField.timeToString(file.lastModified()));
doc.add(fld);
FileInputStream in = new FileInputStream(file);
Reader reader = new BufferedReader(new InputStreamReader(in));
fld = Field.Text("contents", reader);
doc.add(fld);
writer.addDocument(doc);
System.out.println("Added : " + doc.get("path"));
}
writer.optimize();
writer.close();
System.out.println("Has Added Total: " + Fnamelist.length);
}catch(Exception e){
System.out.println(e);
}
}
}
程序對當前路徑下mydoc目錄下所有文件建立索引,其中索引有三個(gè)字段: 文件路徑,
最后修改時(shí)間,文件內容. 建立的索引文件在當前路徑下的myindex目錄
檢索程序:
/*
* Created on 2004-4-26
*
*/
import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.search.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.document.*;
//import com.augmentum.hrms.*;
import java.util.Date;
/**
* @author bell.wang
*
*/
public class SearchFile {
public static void main(String[] args) {
//XMap a = new XMap("");
Analyzer anlzr = new StandardAnalyzer();
try{
Query q = QueryParser.parse("數據庫", "contents", anlzr);
System.out.println("Searching for : " + q.toString("contents"));
Searcher serch = new IndexSearcher("myindex");
Hits hts = serch.search(q);
for(int i=0; i<hts.length(); i++){
Document doc = hts.doc(i);
String path = doc.get("path");
System.out.println("Find: " +i+": "+ path);
System.out.println("Find: " + doc.get("modified"));
System.out.println("Find: " + doc.get("path"));
}
System.out.println("Find Total: " + hts.length());
}catch(Exception e){
System.out.println(e);
}
}
}
程序對索引的contents字段用“數據庫“關(guān)鍵字進(jìn)行查詢(xún),返回
的是所有包含有關(guān)鍵字的文檔集合,分別打印出各個(gè)字段.
上面的程序我用純文本文件測試通過(guò),.txt,.jsp,.html 都可以,
word,pdf 等文件需要經(jīng)過(guò)轉化才能對其進(jìn)行索引。
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。