Lucene學習之一:使用lucene爲數據庫表建立索引,並按關鍵字查詢

最近項目中要用到模糊查詢,開始研究lucene,期間走了好多彎路,總算實現了一個簡單的demo。java

使用的lucene jar包是3.6版本.web

一:創建數據庫表,並加上測試數據。數據庫表:UserInfosql

 

二:新建java project,並引入lucene jar包。http://lucene.apache.org/數據庫

 

三:爲數據庫表創建索引及利用索引查數據:apache

 

import java.io.File;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import org.apache.lucene.store.SimpleFSDirectory;
import com.test.dbc.DBConnection;


public class MakeTableIndex {
public static void main(String[] args) throws IOException, SQLException {
String indexDir = "d:\\lucene\\index";
Connection conn;
DBConnection conn1 = new DBConnection();
conn = conn1.getConnection();
PreparedStatement pstmt = conn
.prepareStatement("SELECT * FROM UserInfo");


ResultSet rs = pstmt.executeQuery();
// 爲表字段創建索引
Directory dir = new SimpleFSDirectory(new File(indexDir));
// 分詞
Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_36);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,
luceneAnalyzer);
iwc.setOpenMode(OpenMode.CREATE);
IndexWriter indexWriter = new IndexWriter(dir, iwc);


while (rs.next()) {
System.out.println("username***" + rs.getString(2));
Document doc = new Document();
doc.add(new Field("ID", rs.getString(1), Field.Store.YES,
Field.Index.ANALYZED));
doc.add(new Field("UserName", rs.getString(2), Field.Store.YES,
Field.Index.ANALYZED));
doc.add(new Field("Hobby", rs.getString(5), Field.Store.YES,
Field.Index.ANALYZED));
indexWriter.addDocument(doc);
}
System.out.println("numDocs" + indexWriter.numDocs());
indexWriter.close();
try {
search();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}

}


// ------------------Search
public static void search() throws Exception {
String  dirPathString="d:\\lucene\\index";
System.out.println(dirPathString);
Directory dir = new SimpleFSDirectory(new File(dirPathString));//查詢分析器  路徑
IndexReader reader = IndexReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser(Version.LUCENE_35, "UserName", new StandardAnalyzer(Version.LUCENE_36));
Query q = parser.parse("張麗");
TopDocs tds = searcher.search(q, 5);
ScoreDoc[] sds = tds.scoreDocs;
for (ScoreDoc sd : sds) {
System.out.println(sd.score);
int docName = sd.doc;
Document doc = searcher.doc(docName);
String UserName = doc.get("UserName");
String Hobby = doc.get("Hobby");
System.out.println("UserName:"+UserName+"---Hobby:"+Hobby);
}
}
}sqlserver

package com.test.dbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
    public static final String DBDRIVER= "com.microsoft.sqlserver.jdbc.SQLServerDriver"; ;
    public static final String DBURL = "jdbc:sqlserver://localhost:1433; DatabaseName=Wang;" ;
    public static final String DBUSER = "sa" ;
    public static final String DBPASS = "sa" ;
    private Connection conn = null ;
    public DBConnection(){        //在構造方法中進行數據庫鏈接
        try{
            Class.forName(DBDRIVER) ;     //加載驅動程序
            conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
        }catch(Exception e){
            e.printStackTrace() ;
        }
    }
    public Connection getConnection(){     //取得數據庫鏈接
        System.out.println("數據庫連接");
        return this.conn ;
    }
    public void close(){
        if(this.conn!=null){                  //數據庫關閉操做,避免空指針異常。
            try{
                this.conn.close() ;
            }catch(Exception e){}
        }
    }
}

 

有幾點問題須要注意:測試

1.創建索引的分詞器和查詢用的分詞器必須一致this

2.創建索引的字段名和查詢的字段名需保持一致,才能找到結果spa

我的認爲,lucene查詢相比在數據庫裏查詢表只是多了創建索引這一步,達到的目的都是從數據庫了檢索出咱們須要的數據。指針

以上僅表明我的觀點,歡迎你們拍磚

相關文章
相關標籤/搜索