J 2 EEプロジェクトではlucene検索エンジンを使用します.

34185 ワード

luceneは最も広く使われているjava検索エンジンです.詳しくはここで紹介しません.以下は主にどのようにエレクトビジネスプロジェクトでluceneを使って検索エンジンとして商品を検索しますか?
私が使っているバージョンは4.4で、ネット上の教程はほとんど3.xですので、参考にしました.
http://blog.csdn.net/name_110/articale/detail/696366
http://davenzhang.com/lucene_tutorial.httmのこの二つの文章は、この4.4がデータベースにアクセスするバージョンを書いています.
まずjdbcのリンクを作成します.
  

   
   
   
   
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JdbcUtil { private static Connection conn = null ; private static final String URL = " jdbc:mysql://127.0.0.1/ecshop?autoReconnect=true&characterEncoding=utf8 " ; private static final String JDBC_DRIVER = " com.mysql.jdbc.Driver " ; private static final String USER_NAME = " root " ; private static final String PASSWORD = "" ; public static Connection getConnection() { try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
   
  
 
 
後に検索クラスを作成します.
 


   
   
   
   

     
     
     
     
import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.TermVector; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.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.store.FSDirectory; import org.apache.lucene.util.Version; import org.wltea.analyzer.lucene.IKAnalyzer; import com.zhuoda.model.SearchBean; import com.zhuoda.util.JdbcUtil; public class SearchLogic { private static Connection conn = null ; private static Statement stmt = null ; private static ResultSet rs = null ; private String searchDir = " E:\\Test\\Index " ; private static File indexFile = null ; private static IndexSearcher searcher = null ; private static Analyzer analyzer = null ; /** * * @return ResultSet * @throws Exception */ public List < SearchBean > getResult(String queryStr) throws Exception { List < SearchBean > result = null ; conn = JdbcUtil.getConnection(); if (conn == null ) { throw new Exception( " " ); } String sql = " select goods_id, goods_name,goods_img from ecs_goods " ; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql); // this.createIndex(rs); // , , , TopDocs topDocs = this .search(queryStr); ScoreDoc[] scoreDocs = topDocs.scoreDocs; result = this .addHits2List(scoreDocs); } catch (Exception e) { e.printStackTrace(); throw new Exception( " sql ! sql : " + sql); } finally { if (rs != null ) rs.close(); if (stmt != null ) stmt.close(); if (conn != null ) conn.close(); } return result; } /** * * @param rs * @throws Exception */ @SuppressWarnings( " deprecation " ) public void createIndex(ResultSet rs) throws Exception { Directory directory = null ; IndexWriter indexWriter = null ; try { indexFile = new File(searchDir); if ( ! indexFile.exists()) { indexFile.mkdir(); } else { deleteDir(indexFile); } directory = FSDirectory.open(indexFile); analyzer = new IKAnalyzer(); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44, analyzer); indexWriter = new IndexWriter(directory, config); Document doc = null ; while (rs.next()) { doc = new Document(); Field id = new Field( " goods_id " , String.valueOf(rs.getInt( " goods_id " )), Field.Store.YES, Field.Index.NOT_ANALYZED, TermVector.NO); Field goods_name = new Field( " goods_name " , rs.getString( " goods_name " ) == null ? "" : rs.getString( " goods_name " ), Field.Store.YES,Field.Index.ANALYZED, TermVector.NO); Field goods_img = new Field( " goods_img " , rs.getString( " goods_img " ) == null ? "" : rs.getString( " goods_img " ), Field.Store.YES,Field.Index.ANALYZED, TermVector.NO); doc.add(id); doc.add(goods_name); doc.add(goods_img); indexWriter.addDocument(doc); } indexWriter.commit(); indexWriter.close(); } catch (Exception e) { e.printStackTrace(); } } private static void deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for ( int i = 0 ; i < children.length; i ++ ) { deleteDir( new File(dir, children[i])); } } dir.delete(); } /** * * @param queryStr * @return * @throws Exception */ private TopDocs search(String queryStr) throws Exception { if (searcher == null ) { indexFile = new File(searchDir); Directory directory = FSDirectory.open(indexFile); IndexReader ireader = DirectoryReader.open(directory); searcher = new IndexSearcher(ireader); } searcher.setSimilarity( new IKSimilarity()); QueryParser parser = new QueryParser(Version.LUCENE_44, " goods_name " , new IKAnalyzer()); Query query = parser.parse(queryStr); TopDocs topDocs = searcher.search(query, 10 ); return topDocs; } /** * List * @param scoreDocs * @return * @throws Exception */ private List < SearchBean > addHits2List(ScoreDoc[] scoreDocs ) throws Exception { List < SearchBean > listBean = new ArrayList < SearchBean > (); SearchBean bean = null ; for ( int i = 0 ; i < scoreDocs.length; i ++ ) { int docId = scoreDocs[i].doc; Document doc = searcher.doc(docId); bean = new SearchBean(); bean.setId(doc.get( " goods_id " )); bean.setGoodsname(doc.get( " goods_name " )); bean.setGoodsImg(doc.get( " goods_img " )); listBean.add(bean); } return listBean; } public List < SearchBean > serachGoods(String words) { SearchLogic logic = new SearchLogic(); List < SearchBean > result = null ; try { Long startTime = System.currentTimeMillis(); result = logic.getResult(words); System.out.println( " searchBean.result.size : " + result.size()); Long endTime = System.currentTimeMillis(); System.out.println( " " + (endTime - startTime) / 1000 ); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } return result; } }
     ,    :

    
    
    
    
import org.apache.lucene.search.similarities.DefaultSimilarity; /** * * IK Analyzer v3.2 * * DefaultSimilarity coord * , , , * */ public class IKSimilarity extends DefaultSimilarity { /** * * */ private static final long serialVersionUID = 7558565500061194774L ; /** (non-Javadoc) * @see org.apache.lucene.search.Similarity#coord(int, int) */ public float coord( int overlap, int maxOverlap) { float overlap2 = ( float )Math.pow( 2 , overlap); float maxOverlap2 = ( float )Math.pow( 2 , maxOverlap); return (overlap2 / maxOverlap2); } }
プロジェクトの に じてビーン、Search Beanを くことができます. には のフィールドのgetsset があればいいです.
つ したいのは、 しいインデックスを する 、 いインデックスファイルを すると、 した が ます.
この はwindows live writerで いたのですが、タグをつけることができなくて、ホームページで したらコードが れてしまいました. です.この をどう するかを っている はメッセージをください.