用Lucene索引數據庫


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的內容。具體代碼如下:

 

 1  public ResultSet getResult(String sql){
 2       try{
 3         Statement stmt = conn.createStatement();
 4         ResultSet rs = stmt.executeQuery(sql);
 5         return rs;
 6       }
 7       catch(SQLException e){
 8         System.out.println(e);
 9       }
10       return null;
11     }

 

然后,為數據庫建立索引。

   首先要定義一個IndexWriter(),它是將索引寫進Lucene自己的數據庫中,它存放的位置是有你自己定義的。在定義IndexWriter 是需要指定它的分析器。Lucene自己自帶有幾個分析器,例如:StandarAnalyzer(),SimpleAnalyzer(), StopAnalyzer()等。它作用是對文本進行分析,判斷如何進行切詞。
接着,要定義一個Document。Document相當於二維表中一行數據一樣。Document里包含的是Field字段,Field相當於數據庫中一列,也就是一個屬性,一個字段。
最后應該對IndexWriter進行優化,方法很簡單,就是writer.optimize().
具體代碼如下:

 1  public void Index(ResultSet rs){
 2       try{
 3         IndexWriter writer = new IndexWriter("d:/index/", getAnalyzer(), true);
 4         while(rs.next()){
 5             Document doc=new Document();
 6             doc.add(Field.Keyword("id",rs.getString("au_id")));
 7             doc.add(Field.Text("name",rs.getString("au_name")));
 8             doc.add(Field.UnIndexed("address",rs.getString("address")));
 9             doc.add(Field.UnIndexed("phone",rs.getString("phone")));
10             doc.add(Field.Text("City",rs.getString("city")));
11             writer.addDocument(doc);
12           }
13         writer.optimize();
14         writer.close();
15       }
16       catch(IOException e){
17         System.out.println(e);
18       }
19       catch(SQLException e){
20         System.out.println(e);
21       }
22     }
23 
24     public Analyzer getAnalyzer(){
25       return new StandardAnalyzer();
26     }

3.為數據庫建立查詢功能

  在類TestLucene中建立一個新的方法searcher(String),它返回的是一個搜索的結構集,相當於數據庫中的ResultSet一樣。它代的參數是你要查詢的內容。這里,我把要查詢的字段寫死了。你可以在添加一個參數表示要查詢的字段。
這里主要有兩個對象IndexSearcher和Query。IndexSearcher是找到索引數據庫,Query是處理搜索,它包含了三個參數:查詢內容,查詢字段,分析器。
具體代碼如下:

 1 public Hits seacher(String queryString){
 2       Hits hits=null;;
 3       try{
 4         IndexSearcher is = new IndexSearcher("D:/index/");
 5         Query query=QueryParser.parse(queryString,"City",getAnalyzer());
 6         hits=is.search(query);
 7       }catch(Exception e){
 8         System.out.print(e);
 9       }
10       return hits;
11     }

4.在web界面下進行查詢並顯示結果

  這里建立一個Jsp頁面TestLucene.jsp進行搜索。

  在TestLucene.jsp頁面中首先引入類

 

 1 <%@ page import="lucenetest.LucentTest"%>
 2 <%@ page import="org.apache.lucene.search.*,org.apache.lucene.document.*" %>
 3 
 4   然后定義一個LuceneTest對象,獲取查詢結果集:
 5 
 6   LucentTest lucent=new LucentTest();
 7   Hits hits=lucent.seacher(request.getParameter("queryString"));
 8 
 9   定義一個Form,建立一個查詢環境:
10 
11 <form action="TestLucene.jsp">
12   <input  type="text" name="queryString"/>
13   <input type="submit" value="搜索"/>
14 </form>
15 
16   顯示查詢結果:
17 
18 <table>
19   <%if(hits!=null){%>
20   <tr>
21     <td>作者號</td>
22     <td>作者名</td>
23     <td>地址</td>
24     <td>電話號碼</td>
25   </tr>
26 
27  <% for(int i=0;i<hits.length();i++){
28     Document doc=hits.doc(i);
29    %>
30     <tr>
31     <td><%=doc.get("id") %></td>
32     <td><%=doc.get("name") %></td>
33     <td><%=doc.get("address") %></td>
34     <td><%=doc.get("phone") %></td>
35   </tr>
36  <% }}%>
37 </table>

 

 

  1 用Lucene-1.3-final為網站數據庫建立索引
  2 
  3 下是看了lnboy寫的《用lucene建立大富翁論壇的全文檢索》后寫的測試代碼。
  4  
  5 為數據庫cwb.mdb建立全文索引的indexdb.jsp 
  6 
  7 <%@ page import ="org.apache.lucene.analysis.standard.*" %>  
  8 <%@ page import="org.apache.lucene.index.*" %> 
  9 <%@ page import="org.apache.lucene.document.*" %> 
 10 <%@ page import="lucene.*" %> 
 11 <%@ page contentType="text/html; charset=GBK" %> 
 12 <% 
 13       long start = System.currentTimeMillis(); 
 14       String aa=getServletContext().getRealPath("/")+"index";    
 15       IndexWriter writer = new IndexWriter(aa, new StandardAnalyzer(), true); 
 16     try { 
 17       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); 
 18 
 19  String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)}
 20        ;DBQ=d://Tomcat 5.0//webapps//zz3zcwbwebhome//WEB-INF//cwb.mdb"; 
 21       Connection conn = DriverManager.getConnection(url); 
 22       Statement stmt = conn.createStatement(); 
 23       ResultSet rs = stmt.executeQuery( 
 24           "select Article_id,Article_name,Article_intro from Article"); 
 25       while (rs.next()) { 
 26              writer.addDocument(mydocument.Document(rs.getString("Article_id"),
 27                 rs.getString("Article_name"),rs.getString("Article_intro"))); 
 28       } 
 29       rs.close(); 
 30       stmt.close(); 
 31       conn.close(); 
 32   
 33       out.println("索引創建完畢");    
 34       writer.optimize(); 
 35       writer.close(); 
 36       out.print(System.currentTimeMillis() - start); 
 37       out.println(" total milliseconds"); 
 38 
 39     } 
 40     catch (Exception e) { 
 41       out.println(" 出錯了 " + e.getClass() + 
 42                          "/n 錯誤信息為: " + e.getMessage()); 
 43     } 
 44  %> 
 45 
 46 用於顯示查詢結果的aftsearch.jsp 
 47 <%@ page import="org.apache.lucene.search.*" %> 
 48 <%@ page import="org.apache.lucene.document.*" %> 
 49 <%@ page import="lucene.*" %> 
 50 <%@ page import = "org.apache.lucene.analysis.standard.*" %>  
 51 <%@ page import="org.apache.lucene.queryParser.QueryParser" %> 
 52 <%@ page contentType="text/html; charset=GBK" %> 
 53 <% 
 54     String keyword=request.getParameter("keyword"); 
 55      keyword=new String(keyword.getBytes("ISO8859_1"));  
 56       out.println(keyword); 
 57    try { 
 58        String aa=getServletContext().getRealPath("/")+"index";    
 59       Searcher searcher = new IndexSearcher(aa); 
 60       Query query = QueryParser.parse(keyword, "Article_name", new StandardAnalyzer()); 
 61      
 62       out.println("正在查找: " + query.toString("Article_name")+"<br>"); 
 63       Hits hits = searcher.search(query); 
 64       System.out.println(hits.length() + " total matching documents"); 
 65       java.text.NumberFormat format = java.text.NumberFormat.getNumberInstance(); 
 66       for (int i = 0; i < hits.length(); i++) { 
 67         //開始輸出查詢結果 
 68         Document doc = hits.doc(i); 
 69         out.println(doc.get("Article_id")); 
 70         out.println("准確度為:" + format.format(hits.score(i) * 100.0) + "%"); 
 71         out.println(doc.get("Article_name")+"<br>"); 
 72        // out.println(doc.get("Article_intro")); 
 73       } 
 74     }catch (Exception e) { 
 75       out.println(" 出錯了 " + e.getClass() +"/n 錯誤信息為: " + e.getMessage()); 
 76     } 
 77 %> 
 78 
 79 輔助類: 
 80 package lucene; 
 81 import org.apache.lucene.document.Document; 
 82 import org.apache.lucene.document.Field; 
 83 import org.apache.lucene.document.DateField; 
 84 
 85 public class mydocument { 
 86 public static Document Document(String Article_id,String Article_name,String Article_intro){ 
 87      Document doc = new Document(); 
 88       doc.add(Field.Keyword("Article_id", Article_id)); 
 89       doc.add(Field.Text("Article_name", Article_name)); 
 90       doc.add(Field.Text("Article_intro", Article_intro)); 
 91       return doc; 
 92   } 
 93   public mydocument() { 
 94   } 
 95 }
 96 
 97 用lucene為數據庫搜索建立增量索引
 98 
 99 用 lucene 建立索引不可能每次都重新開始建立,而是按照新增加的記錄,一次次的遞增
100 建立索引的IndexWriter類,有三個參數 
101 
102 IndexWriter writer = new IndexWriter(path, new StandardAnalyzer(),isEmpty);
103 
104 
105 其中第三個參數是bool型的,指定它可以確定是增量索引,還是重建索引.
106 對於從數據庫中讀取的記錄,譬如要為文章建立索引,我們可以記錄文章的id號,然后下次再次建立索引的時候讀取存下的id號,從此id后往下繼續增加索引,邏輯如下.
107 
108 建立增量索引,主要代碼如下
109 
110 public void createIndex(String path)
111 {
112      Statement myStatement = null;
113      String articleId="0";
114      //讀取文件,獲得文章id號碼,這里只存最后一篇索引的文章id
115     try { 
116         FileReader fr = new FileReader("**.txt");
117         BufferedReader br = new BufferedReader(fr);                 
118         articleId=br.readLine();
119         if(articleId==null||articleId=="")
120         articleId="0";
121         br.close();
122         fr.close(); 
123       } catch (IOException e) { 
124         System.out.println("error343!");
125         e.printStackTrace();
126       }
127     try {
128         //sql語句,根據id讀取下面的內容
129         String sqlText = "*****"+articleId;
130         myStatement = conn.createStatement();
131         ResultSet rs = myStatement.executeQuery(sqlText);
132        //寫索引
133         while (rs.next()) {
134          Document doc = new Document();
135          doc.add(Field.Keyword("**", DateAdded));
136          doc.add(Field.Keyword("**", articleid));
137          doc.add(Field.Text("**", URL));    
138          doc.add(Field.Text("**", Content));
139          doc.add(Field.Text("**", Title));    
140          try{
141             writer.addDocument(doc);
142           }
143           catch(IOException e){
144             e.printStackTrace();
145          }
146            //將我索引的最后一篇文章的id寫入文件
147           try { 
148            FileWriter fw = new FileWriter("**.txt");
149            PrintWriter out = new PrintWriter(fw);    
150            out.close();
151            fw.close();
152            } catch (IOException e) { 
153              e.printStackTrace();
154            }
155          }
156             ind.Close();
157             System.out.println("ok.end");
158          }
159          catch (SQLException e){
160             e.printStackTrace();
161         }
162         finally {
163             //數據庫關閉操作
164         }        
165     }
166 
167 
168 然后控制是都建立增量索引的時候根據能否都到id值來設置IndexWriter的第三個參數為true 或者是false
169 
170  boolean isEmpty = true;
171  try { 
172     FileReader fr = new FileReader("**.txt");
173     BufferedReader br = new BufferedReader(fr);                 
174     if(br.readLine()!= null) {
175         isEmpty = false;
176      }
177      br.close();
178      fr.close(); 
179     } catch (IOException e) { 
180        e.printStackTrace();
181   }
182             
183   writer = new IndexWriter(Directory, new StandardAnalyzer(),isEmpty);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM