1.寫一段傳統的JDBC程序,將每條的用戶信息從數據庫讀取出來
2.針對每條用戶記錄,建立一個lucene document
Document doc = new Document();
並根據你的需要,將用戶信息的各個字段對應luncene document中的field 進行添加,如:
doc.add(new Field("NAME","USERNAME",Field.Store.YES,Field.Index.UN_TOKENIZED));
然後將該條doc加入到索引中, 如: luceneWriter.addDocument(doc);
這樣就建立了lucene的索引庫
3.編寫對索引庫的搜索程序(看lucene文檔),通過對lucene的索引庫的查找,你可以快速找到對應記錄的ID
4.通過ID到數據庫中查找相關記錄
用Lucene索引數據庫
Lucene,作爲一種全文搜索的輔助工具,爲我們進行條件搜索,無論是像Google,Baidu之類的搜索引 擎,還是論壇中的搜索功能,還是其它C/S架構的搜索,都帶來了極大的便利和比較高的效率。本文主要是利用Lucene對MS Sql Server 2000進行建立索引,然後進行全文索引。至於數據庫的內容,可以是網頁的內容,還是其它的。本文中數據庫的內容是圖書館管理系統中的某個作者表- Authors表。
因爲考慮到篇幅的問題,所以該文不會講的很詳細,也不可能講的很深。
本文以這樣的結構進行:
1.介紹數據庫中Authors表的結構
2.爲數據庫建立索引
3.爲數據庫建立查詢功能
4.在web界面下進行查詢並顯示結果
1.介紹數據庫中Authors表的結構
字段名稱 字段類型 字段含義
Au_id Varchar(11) 作者號
Au_name Varchar(60) 作者名
Phone Char(12) 電話號碼
Address Varchar(40) 地址
City Varchar(20) 城市
State Char(2) 省份
Zip Char(5) 郵編
contract Bit(1) 外鍵(關係不大)
表中的部分內容:
2.爲數據庫建立索引
首先建立一個類TestLucene.java。這個類就是對數據庫進行建立索引,編寫查詢條件等。
當然,最開始就是建立數據庫連接。連接代碼這裏就省略了。^_^
接着,新建一個方法getResutl(String),它返回的是數據庫表Authors的內容。具體代碼如下:
public ResultSet getResult(String sql){
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;
}
catch(SQLException e){
System.out.println(e);
}
return null;
}
然後,爲數據庫建立索引。
首先要定義一個IndexWriter(),它是將索引寫進Lucene自己的數據庫中,它存放的位置是有你自己定義的。在定義IndexWriter 是需要指定它的分析器。Lucene自己自帶有幾個分析器,例如:StandarAnalyzer(),SimpleAnalyzer(), StopAnalyzer()等。它作用是對文本進行分析,判斷如何進行切詞。
接着,要定義一個Document。Document相當於二維表中一行數據一樣。Document裏包含的是Field字段,Field相當於數據庫中一列,也就是一個屬性,一個字段。
最後應該對IndexWriter進行優化,方法很簡單,就是writer.optimize().
具體代碼如下:
public void Index(ResultSet rs){
try{
IndexWriter writer = new IndexWriter("d:/index/", getAnalyzer(), true);
while(rs.next()){
Document doc=new Document();
doc.add(Field.Keyword("id",rs.getString("au_id")));
doc.add(Field.Text("name",rs.getString("au_name")));
doc.add(Field.UnIndexed("address",rs.getString("address")));
doc.add(Field.UnIndexed("phone",rs.getString("phone")));
doc.add(Field.Text("City",rs.getString("city")));
writer.addDocument(doc);
}
writer.optimize();
writer.close();
}
catch(IOException e){
System.out.println(e);
}
catch(SQLException e){
System.out.println(e);
}
}
public Analyzer getAnalyzer(){
return new StandardAnalyzer();
}
3.爲數據庫建立查詢功能
在類TestLucene中建立一個新的方法searcher(String),它返回的是一個搜索的結構集,相當於數據庫中的ResultSet一樣。它代的參數是你要查詢的內容。這裏,我把要查詢的字段寫死了。你可以在添加一個參數表示要查詢的字段。
這裏主要有兩個對象IndexSearcher和Query。IndexSearcher是找到索引數據庫,Query是處理搜索,它包含了三個參數:查詢內容,查詢字段,分析器。
具體代碼如下:
public Hits seacher(String queryString){
Hits hits=null;;
try{
IndexSearcher is = new IndexSearcher("D:/index/");
Query query=QueryParser.parse(queryString,"City",getAnalyzer());
hits=is.search(query);
}catch(Exception e){
System.out.print(e);
}
return hits;
}
4.在web界面下進行查詢並顯示結果
這裏建立一個Jsp頁面TestLucene.jsp進行搜索。
在TestLucene.jsp頁面中首先引入類
<%@ page import="lucenetest.LucentTest"%>
<%@ page import="org.apache.lucene.search.*,org.apache.lucene.document.*" %>
然後定義一個LuceneTest對象,獲取查詢結果集:
LucentTest lucent=new LucentTest();
Hits hits=lucent.seacher(request.getParameter("queryString"));
定義一個Form,建立一個查詢環境:
<form action="TestLucene.jsp">
<input type="text" name="queryString"/>
<input type="submit" value="搜索"/>
</form>
顯示查詢結果:
<table>
<%if(hits!=null){%>
<tr>
<td>作者號</td>
<td>作者名</td>
<td>地址</td>
<td>電話號碼</td>
</tr>
<% for(int i=0;i<hits.length();i++){
Document doc=hits.doc(i);
%>
<tr>
<td><%=doc.get("id") %></td>
<td><%=doc.get("name") %></td>
<td><%=doc.get("address") %></td>
<td><%=doc.get("phone") %></td>
</tr>
<% }}%>
</table>
用Lucene-1.3-final爲網站數據庫建立索引
下是看了lnboy寫的《用lucene建立大富翁論壇的全文檢索》後寫的測試代碼。
爲數據庫cwb.mdb建立全文索引的indexdb.jsp
<%@ page import ="org.apache.lucene.analysis.standard.*" %>
<%@ page import="org.apache.lucene.index.*" %>
<%@ page import="org.apache.lucene.document.*" %>
<%@ page import="lucene.*" %>
<%@ page contentType="text/html; charset=GBK" %>
<%
long start = System.currentTimeMillis();
String aa=getServletContext().getRealPath("/")+"index";
IndexWriter writer = new IndexWriter(aa, new StandardAnalyzer(), true);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)}
;DBQ=d://Tomcat 5.0//webapps//zz3zcwbwebhome//WEB-INF//cwb.mdb";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select Article_id,Article_name,Article_intro from Article");
while (rs.next()) {
writer.addDocument(mydocument.Document(rs.getString("Article_id"),
rs.getString("Article_name"),rs.getString("Article_intro")));
}
rs.close();
stmt.close();
conn.close();
out.println("索引創建完畢");
writer.optimize();
writer.close();
out.print(System.currentTimeMillis() - start);
out.println(" total milliseconds");
}
catch (Exception e) {
out.println(" 出錯了 " + e.getClass() +
"/n 錯誤信息爲: " + e.getMessage());
}
%>
用於顯示查詢結果的aftsearch.jsp
<%@ page import="org.apache.lucene.search.*" %>
<%@ page import="org.apache.lucene.document.*" %>
<%@ page import="lucene.*" %>
<%@ page import = "org.apache.lucene.analysis.standard.*" %>
<%@ page import="org.apache.lucene.queryParser.QueryParser" %>
<%@ page contentType="text/html; charset=GBK" %>
<%
String keyword=request.getParameter("keyword");
keyword=new String(keyword.getBytes("ISO8859_1"));
out.println(keyword);
try {
String aa=getServletContext().getRealPath("/")+"index";
Searcher searcher = new IndexSearcher(aa);
Query query = QueryParser.parse(keyword, "Article_name", new StandardAnalyzer());
out.println("正在查找: " + query.toString("Article_name")+"<br>");
Hits hits = searcher.search(query);
System.out.println(hits.length() + " total matching documents");
java.text.NumberFormat format = java.text.NumberFormat.getNumberInstance();
for (int i = 0; i < hits.length(); i++) {
//開始輸出查詢結果
Document doc = hits.doc(i);
out.println(doc.get("Article_id"));
out.println("準確度爲:" + format.format(hits.score(i) * 100.0) + "%");
out.println(doc.get("Article_name")+"<br>");
// out.println(doc.get("Article_intro"));
}
}catch (Exception e) {
out.println(" 出錯了 " + e.getClass() +"/n 錯誤信息爲: " + e.getMessage());
}
%>
輔助類:
package lucene;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.DateField;
public class mydocument {
public static Document Document(String Article_id,String Article_name,String Article_intro){
Document doc = new Document();
doc.add(Field.Keyword("Article_id", Article_id));
doc.add(Field.Text("Article_name", Article_name));
doc.add(Field.Text("Article_intro", Article_intro));
return doc;
}
public mydocument() {
}
}
用lucene爲數據庫搜索建立增量索引
用 lucene 建立索引不可能每次都重新開始建立,而是按照新增加的記錄,一次次的遞增
建立索引的IndexWriter類,有三個參數
IndexWriter writer = new IndexWriter(path, new StandardAnalyzer(),isEmpty);
其中第三個參數是bool型的,指定它可以確定是增量索引,還是重建索引.
對於從數據庫中讀取的記錄,譬如要爲文章建立索引,我們可以記錄文章的id號,然後下次再次建立索引的時候讀取存下的id號,從此id後往下繼續增加索引,邏輯如下.
建立增量索引,主要代碼如下
public void createIndex(String path)
{
Statement myStatement = null;
String articleId="0";
//讀取文件,獲得文章id號碼,這裏只存最後一篇索引的文章id
try {
FileReader fr = new FileReader("**.txt");
BufferedReader br = new BufferedReader(fr);
articleId=br.readLine();
if(articleId==null||articleId=="")
articleId="0";
br.close();
fr.close();
} catch (IOException e) {
System.out.println("error343!");
e.printStackTrace();
}
try {
//sql語句,根據id讀取下面的內容
String sqlText = "*****"+articleId;
myStatement = conn.createStatement();
ResultSet rs = myStatement.executeQuery(sqlText);
//寫索引
while (rs.next()) {
Document doc = new Document();
doc.add(Field.Keyword("**", DateAdded));
doc.add(Field.Keyword("**", articleid));
doc.add(Field.Text("**", URL));
doc.add(Field.Text("**", Content));
doc.add(Field.Text("**", Title));
try{
writer.addDocument(doc);
}
catch(IOException e){
e.printStackTrace();
}
//將我索引的最後一篇文章的id寫入文件
try {
FileWriter fw = new FileWriter("**.txt");
PrintWriter out = new PrintWriter(fw);
out.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ind.Close();
System.out.println("ok.end");
}
catch (SQLException e){
e.printStackTrace();
}
finally {
//數據庫關閉操作
}
}
然後控制是都建立增量索引的時候根據能否都到id值來設置IndexWriter的第三個參數爲true 或者是false
boolean isEmpty = true;
try {
FileReader fr = new FileReader("**.txt");
BufferedReader br = new BufferedReader(fr);
if(br.readLine()!= null) {
isEmpty = false;
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
writer = new IndexWriter(Directory, new StandardAnalyzer(),isEmpty);
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/feijianxia/archive/2008/10/23/3128942.aspx