乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      用Lucene檢索數(shù)據(jù)庫

       漂在北方的狼 2008-01-31
      1.寫一段傳統(tǒng)的JDBC程序,講每條的用戶信息從數(shù)據(jù)庫讀取出來
      2.針對每條用戶記錄,建立一個lucene document
      Document doc = new Document();
      并根據(jù)你的需要,將用戶信息的各個字段對應(yīng)luncene document中的field 進(jìn)行添加,如:
      doc.add(new Field("NAME","USERNAME",Field.Store.YES,Field.Index.UN_TOKENIZED));
      然后將該條doc加入到索引中, 如: luceneWriter.addDocument(doc);
      這樣就建立了lucene的索引庫
      3.編寫對索引庫的搜索程序(看lucene文檔),通過對lucene的索引庫的查找,你可以快速找到對應(yīng)記錄的ID
      4.通過ID到數(shù)據(jù)庫中查找相關(guān)記錄
      用Lucene索引數(shù)據(jù)庫

      Lucene,作為一種全文搜索的輔助工具,為我們進(jìn)行條件搜索,無論是像Google,Baidu之類的搜索引擎,還是論壇中的搜索功能,還是其它 C/S架構(gòu)的搜索,都帶來了極大的便利和比較高的效率。本文主要是利用Lucene對MS Sql Server 2000進(jìn)行建立索引,然后進(jìn)行全文索引。至于數(shù)據(jù)庫的內(nèi)容,可以是網(wǎng)頁的內(nèi)容,還是其它的。本文中數(shù)據(jù)庫的內(nèi)容是圖書館管理系統(tǒng)中的某個作者表- Authors表。

        因為考慮到篇幅的問題,所以該文不會講的很詳細(xì),也不可能講的很深。

        本文以這樣的結(jié)構(gòu)進(jìn)行:

        1.介紹數(shù)據(jù)庫中Authors表的結(jié)構(gòu)

        2.為數(shù)據(jù)庫建立索引

        3.為數(shù)據(jù)庫建立查詢功能

        4.在web界面下進(jìn)行查詢并顯示結(jié)果

        1.介紹數(shù)據(jù)庫中Authors表的結(jié)構(gòu)

      字段名稱         字段類型         字段含義

      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)                外鍵(關(guān)系不大)

      表中的部分內(nèi)容: 

        2.為數(shù)據(jù)庫建立索引

        首先建立一個類TestLucene.java。這個類就是對數(shù)據(jù)庫進(jìn)行建立索引,編寫查詢條件等。

        當(dāng)然,最開始就是建立數(shù)據(jù)庫連接。連接代碼這里就省略了。^_^

        接著,新建一個方法getResutl(String),它返回的是數(shù)據(jù)庫表Authors的內(nèi)容。具體代碼如下:

          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;
          }

        然后,為數(shù)據(jù)庫建立索引。

        首先要定義一個IndexWriter(),它是將索引寫進(jìn)Lucene自己的數(shù)據(jù)庫中,它存放的位置是有你自己定義的。在定義 IndexWriter 是需要指定它的分析器。Lucene自己自帶有幾個分析器,例如:StandarAnalyzer(),SimpleAnalyzer(), StopAnalyzer()等。它作用是對文本進(jìn)行分析,判斷如何進(jìn)行切詞。
      接著,要定義一個Document。Document相當(dāng)于二維表中一行數(shù)據(jù)一樣。Document里包含的是Field字段,F(xiàn)ield相當(dāng)于數(shù)據(jù)庫中一列,也就是一個屬性,一個字段。
      最后應(yīng)該對IndexWriter進(jìn)行優(yōu)化,方法很簡單,就是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.為數(shù)據(jù)庫建立查詢功能

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

        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界面下進(jìn)行查詢并顯示結(jié)果

        這里建立一個Jsp頁面TestLucene.jsp進(jìn)行搜索。

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


      <%@ page import="lucenetest.LucentTest"%>
      <%@ page import="org.apache.lucene.search.*,org.apache.lucene.document.*" %>

        然后定義一個LuceneTest對象,獲取查詢結(jié)果集:

        LucentTest lucent=new LucentTest();
        Hits hits=lucent.seacher(request.getParameter("queryString"));

        定義一個Form,建立一個查詢環(huán)境:

      <form action="TestLucene.jsp">
        <input  type="text" name="queryString"/>
        <input type="submit" value="搜索"/>
      </form>

        顯示查詢結(jié)果:

      <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為網(wǎng)站數(shù)據(jù)庫建立索引

      下是看了lnboy寫的《用lucene建立大富翁論壇的全文檢索》后寫的測試代碼。
       
      為數(shù)據(jù)庫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("索引創(chuàng)建完畢");    
            writer.optimize(); 
            writer.close(); 
            out.print(System.currentTimeMillis() - start); 
            out.println(" total milliseconds"); 

          } 
          catch (Exception e) { 
            out.println(" 出錯了 " + e.getClass() + 
                               "\n 錯誤信息為: " + e.getMessage()); 
          } 
       %> 

      用于顯示查詢結(jié)果的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++) { 
              //開始輸出查詢結(jié)果 
              Document doc = hits.doc(i); 
              out.println(doc.get("Article_id")); 
              out.println("準(zhǔn)確度為:" + 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為數(shù)據(jù)庫搜索建立增量索引

      用 lucene 建立索引不可能每次都重新開始建立,而是按照新增加的記錄,一次次的遞增
      建立索引的IndexWriter類,有三個參數(shù) 

      IndexWriter writer = new IndexWriter(path, new StandardAnalyzer(),isEmpty);

      其中第三個參數(shù)是bool型的,指定它可以確定是增量索引,還是重建索引.
      對于從數(shù)據(jù)庫中讀取的記錄,譬如要為文章建立索引,我們可以記錄文章的id號,然后下次再次建立索引的時候讀取存下的id號,從此id后往下繼續(xù)增加索引,邏輯如下.

      建立增量索引,主要代碼如下
      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語句,根據(jù)id讀取下面的內(nèi)容
              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 {
                  
      //數(shù)據(jù)庫關(guān)閉操作
              }        
          }

      然后控制是都建立增量索引的時候根據(jù)能否都到id值來設(shè)置IndexWriter的第三個參數(shù)為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);

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多