spring+hibernate+compass

    首先是spring與compass的集成配置文件:applicationContext-compass.xml

Xml代碼  收藏代碼
  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>   
  2. < beans   xmlns = "http://www.springframework.org/schema/beans"   
  3.     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:context = "http://www.springframework.org/schema/context"   
  5.     xsi:schemaLocation ="http://www.springframework.org/schema/beans   
  6.                 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
  7.         default-lazy-init = "true" >       
  8.       
  9.     <!-- 配置compass註解 -->   
  10.     < bean   id = "annotationConfiguration"   class = "org.compass.annotations.config.CompassAnnotationsConfiguration" >   
  11.     </ bean >   
  12.     <!-- 配置compass bean -->   
  13.     < bean   id = "compass"   class = "org.compass.spring.LocalCompassBean" >   
  14.         <!-- 定義索引存放路徑 -->   
  15.         < property   name = "connection" >   
  16.           < value > file://${index.path} </ value >   
  17.         </ property >   
  18.         <!-- 配置需要創建索引的實體 -->   
  19.         < property   name = "classMappings" >   
  20.           < list >           
  21.              < value > com.***.mobile.entity.KnowledgeInfo </ value >   
  22.              < value > com.***.mobile.entity.ChannelInfo </ value >   
  23.              < value > com.***.mobile.entity.MobileBaseEntity </ value >   
  24.              < value > com.***.mobile.entity.BaseEntity </ value >   
  25.              < value > com.***.mobile.entity.BusLine </ value >   
  26.           </ list >   
  27.         </ property >   
  28.         < property   name = "compassConfiguration"   ref = "annotationConfiguration" > </ property >   
  29.         < property   name = "compassSettings" >   
  30.          < props >   
  31.           <!-- compass事務工廠 -->   
  32.           < prop   key = "compass.transaction.factory" > org.compass.spring.transaction.SpringSyncTransactionFactory </ prop >   
  33.           <!-- paoding分詞器 -->   
  34.           < prop   key = "compass.engine.analyzer.MMAnalyzer.CustomAnalyzer" > net.paoding.analysis.analyzer.PaodingAnalyzer </ prop >   
  35.           <!-- 設置高亮顯示 -->   
  36.           < prop   key = "compass.engine.highlighter.default.formatter.simple.pre" > <![CDATA[<font color="#cc0033"><b>]]> </ prop >    
  37.           < prop   key = "compass.engine.highlighter.default.formatter.simple.post" > <![CDATA[</b></font>]]> </ prop >              
  38.          </ props >   
  39.         </ property >   
  40.         < property   name = "transactionManager"   ref = "transactionManager"   />   
  41.     </ bean >   
  42.     <!-- 用Hibernate3事件系統,支持Real Time Data Mirroring.經Hiberante改變的數據會自動被反射到索引裏面 -->   
  43.     < bean   id = "hibernateGpsDevice"   class = "org.compass.gps.device.hibernate.dep.Hibernate3GpsDevice" >   
  44.             < property   name = "name" >   
  45.                     < value > hibernateDevice </ value >   
  46.             </ property >   
  47.             < property   name = "sessionFactory"   ref = "sessionFactory"   />   
  48.             < property   name = "mirrorDataChanges" >   
  49.                 < value > true </ value >   
  50.             </ property >   
  51.         </ bean >   
  52.      <!-- 同步更新索引 -->   
  53.      < bean   id = "compassGps"   class = "org.compass.gps.impl.SingleCompassGps"   init-method = "start"   destroy-method = "stop" >   
  54.     < property   name = "compass"   ref = "compass"   />   
  55.     < property   name = "gpsDevices" >   
  56.         < list >   
  57.             < bean   class = "org.compass.spring.device.hibernate.dep.SpringHibernate3GpsDevice" >   
  58.                 < property   name = "name"   value = "hibernateDevice" />   
  59.                 < property   name = "sessionFactory"   ref = "sessionFactory" />   
  60.             </ bean >   
  61.         </ list >   
  62.     </ property >   
  63.      </ bean >   
  64.      < bean   id = "compassTemplate"   class = "org.compass.core.CompassTemplate" >   
  65.         < property   name = "compass"   ref = "compass"   />   
  66.           
  67.      </ bean >   
  68. </ beans >   

 接着是實體的compass註解,將需要創建索引的實體及實體屬性標註:

Java代碼  收藏代碼
  1. @Entity   
  2. @Table (name= "B_ENTITY_BASE" )  
  3. @Searchable   
  4. public   class  MobileBaseEntity  implements  Serializable {  
  5.   
  6.     private   static   final   long  serialVersionUID = -5594658438463757978L;  
  7.   
  8.     @SearchableId   
  9.     protected  String id;  
  10.     @SearchableProperty (name =  "keys" )  
  11.     protected  String name;  
  12.     @SearchableProperty (index = Index.NO, store = Store.YES)  
  13.     protected  String address;  
  14.     protected  String phone;  
  15.     protected  String description;  
  16.     @SearchableProperty (index = Index.NO, store = Store.YES)  
  17.     protected  Double longitude;  
  18.     @SearchableProperty (index = Index.NO, store = Store.YES)  
  19.     protected  Double latitude;  
  20.     @SearchableProperty (index = Index.NO, store = Store.YES)  
  21.     protected  String type;  
  22.     protected  String channel;  
  23.     protected  String knowledgeId;  
  24.     protected  String stauts; //0審覈退回,1審覈中,2正常   
  25. }  

@SearchableId:不要求定義搜索的元數據;

@SearchableProperty(name = "keys"):屬性索引的別名,這個別名在做查詢的時候會用到,我們可以把多個實體類的多個屬性定義爲同一個別名來做全文檢索;

@SearchableProperty(index = Index.NO, store = Store.YES):保存這個屬性的值,但不作爲索引。index = Index.XXX,這個有幾種策略,1: NOT_ANALYZED ,不分詞但創建索引;2:ANALYZED,分詞並創建索引。

@SearchableComponent:關聯複合索引,用以複合類型;

@ SearchableReference:用以引用類型。

接下來就是使用compass的API來做數據查詢,首先是模糊匹配查詢,

Java代碼  收藏代碼
  1. List<BusLine> busLineList =  new  ArrayList<BusLine>();  
  2.         Compass compass = this .compassTemplate.getCompass();  
  3.         CompassSession compassSession = compass.openSession();  
  4.         CompassQueryBuilder queryBuilder = compassSession.queryBuilder();  
  5.                                 //指定查詢實體   
  6.         CompassQuery queryAlias = queryBuilder.alias(BusLine.class .getSimpleName());  
  7.         CompassBooleanQueryBuilder boolQueryBuilder = queryBuilder.bool();  
  8.         boolQueryBuilder.addMust(queryAlias);  
  9.         boolQueryBuilder.addMust(queryBuilder.wildcard("baseEntityKeys" "*" +value+ "*" ));  
  10.         CompassHits compassHits = boolQueryBuilder.toQuery().hits();  
  11.         if (compassHits !=  null  && compassHits.length() >  0 ) {  
  12.             for ( int  i =  0 ; i < compassHits.length(); i++) {  
  13.                 BusLine line = (BusLine)compassHits.data(i);  
  14.                 busLineList.add(line);  
  15.             }  
  16.         }  
  17.         compassSession.close();  
  18.         return  busLineList;  

 至於是使用模糊匹配查詢還是全文檢索,這需要根據應用場景來選擇,能使用模糊匹配的話儘量使用,全文檢索的代價比模糊匹配要高。全文檢索的例子:

Java代碼  收藏代碼
  1. String keywords = keyword.trim();  
  2. List<KnowledgeInfo> result = new  ArrayList<KnowledgeInfo>();  
  3. Properties prop = PropertyUtil.readPropertyFile();  
  4. String type = prop.getProperty("knowledge.zc.type" );  
  5. ChannelInfo channel = channelInfoService.getChannelById(type);  
  6. Compass compass = this .compassTemplate.getCompass();  
  7. CompassSession session = compass.openSession();  
  8. CompassQueryBuilder builder = session.queryBuilder();     
  9. CompassBooleanQueryBuilder boolBuidler = builder.bool();  
  10. boolBuidler.addMust(builder.wildcard("sort" , channel.getSort()+ "*" ));  
  11. if (keywords !=  null  && ! "" .equals(keywords)) {  
  12.     String[] array = keywords.split(" " );  
  13.     if  (array !=  null  && array.length >  0 ) {  
  14.         for  (String value : array) {  
  15.             if  (value !=  null  && StringUtils.isNotEmpty(value.trim())) {  
  16.     boolBuidler.addMust(builder.queryString("keys:"  + value).toQuery());  
  17.             }  
  18.         }  
  19.     }  
  20.     CompassHits hits = boolBuidler.toQuery().hits();  
  21.     if  (hits !=  null  && hits.length() >  0 ) {  
  22.         for  ( int  i =  0 ; i < hits.length(); i++) {  
  23.             KnowledgeInfo info = (KnowledgeInfo) hits.data(i);  
  24.             String ht = hits.highlighter(i).fragment("keys" );  
  25.             if  ( null  != ht) {  
  26.                 info.setKeywords(ht);  
  27.             }  
  28.             result.add(info);  
  29.         }  
  30.     }  
  31. }  
  32. session.close();  
  33. return  result;  

 compass一個簡單的應用就完成了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章