hibernate search 例子

阅读更多

1、开发环境:spring2.5、hibernate3.3.1GA、hibernateSearch3.1.0GA;

2、开发是基于maven上开发的,首先新建一个web工程,添加maven支持,在pom.xml中添加一下几个依赖包:

Java代码 复制代码  收藏代码
  1.        
  2.     
  3.       org.apache.openejb  
  4.       javaee-api  
  5.       5.0-1  
  6.       provided  
  7.       
  8.             
  9.     org.hibernate    
  10.     hibernate-search    
  11.     3.1.0.GA    
  12.         
  13.         
  14.         org.hibernate    
  15.         hibernate-annotations    
  16.         3.4.0.GA    
  17.           
  18.       
  19.     
  20.        
  21.     
  22.     
  23.     org.apache.lucene    
  24.     lucene-analyzers    
  25.     3.0.1    
  26.     
  27.     
  28.     org.apache.lucene    
  29.     lucene-highlighter    
  30.     3.0.1    
  31.     
  32.     
     
  
      org.apache.openejb
      javaee-api
      5.0-1
      provided
    
          
    org.hibernate  
    hibernate-search  
    3.1.0.GA  
	  
	  
	    org.hibernate  
	    hibernate-annotations  
	    3.4.0.GA  
	    
	
  
     
  
  
    org.apache.lucene  
    lucene-analyzers  
    3.0.1  
  
  
    org.apache.lucene  
    lucene-highlighter  
    3.0.1  
  
  



其他就是hibernate+spring的配置了;
注意一点的就是在配置文件hibernate的属性后面加上索引的监听和索引存放的位置,如:

Java代码 复制代码  收藏代码
  1.   
  2.     "sessionFactory"  
  3.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  4.         "dataSource">  
  5.             "dataSource" />  
  6.           
  7.         "hibernateProperties">  
  8.               
  9.                 "hibernate.dialect">  
  10.                     ${hibernate.dialect}  
  11.                   
  12.                 "hibernate.hbm2ddl.auto">  
  13.                     ${hibernate.hbm2ddl.auto}  
  14.                   
  15.                 "hibernate.show_sql">  
  16.                     ${hibernate.show_sql}  
  17.                   
  18.                 "hibernate.use_sql_comments">  
  19.                     ${hibernate.use_sql_comments}  
  20.                   
  21.                 "hibernate.use_outer_join">  
  22.                     ${hibernate.use_outer_join}  
  23.                   
  24.                 "hibernate.current_session_context_class">  
  25.                     ${hibernate.current.session.context.class}  
  26.                   
  27.                 "connection.autoReconnect">  
  28.                     ${connection.autoReconnect}  
  29.                    
  30.                 "connection.autoReconnectForPools">  
  31.                     ${connection.autoReconnectForPools}  
  32.                    
  33.                 "connection.is-connection-validation-required">  
  34.                     ${connection.is-connection-validation-required}  
  35.                    
  36.                   
  37.                   
  38.                 "hibernate.search.default.directory_provider">  
  39.                     org.hibernate.search.store.FSDirectoryProvider  
  40.                   
  41.                 "hibernate.search.default.indexBase">  
  42.                     d:/JAVA/hibernateIndex  
  43.                   
  44.                    
  45.               
  46.           
  47.           
  48.           
  49.         "eventListeners">    
  50.                 
  51.                 "post-update">    
  52.                     class="org.hibernate.search.event.FullTextIndexEventListener" />    
  53.                     
  54.                 "post-insert">    
  55.                     class="org.hibernate.search.event.FullTextIndexEventListener" />    
  56.                     
  57.                 "post-delete">    
  58.                     class="org.hibernate.search.event.FullTextIndexEventListener" />    
  59.                     
  60.                 
  61.           
  62.           
  63.         "mappingDirectoryLocations">  
  64.               
  65.                 ${hibernate.mappingDirectoryLocations}  
  66.               
  67.           
  68.       

	
		
			
		
		
			
				
					${hibernate.dialect}
				
				
					${hibernate.hbm2ddl.auto}
				
				
					${hibernate.show_sql}
				
				
					${hibernate.use_sql_comments}
				
				
					${hibernate.use_outer_join}
				
				
					${hibernate.current.session.context.class}
				
				
					${connection.autoReconnect}
				 
        		
        			${connection.autoReconnectForPools}
        		 
        		
        			${connection.is-connection-validation-required}
        		 
        		
        		
        		
					org.hibernate.search.store.FSDirectoryProvider
				
				
					d:/JAVA/hibernateIndex
				
				 
			
		
		
		
		  
              
                  
                      
                  
                  
                      
                  
                  
                      
                  
              
		
		
		
			
				${hibernate.mappingDirectoryLocations}
			
		
	



这时启动如果报slf4j错误,可能是你的slf4j包冲突,需要把你lib里相关的jar包删了,在maven支持中还剩下slf4j-api-1.4.2.jar,需要导入slf4j-logging-1.4.2.jar包,如果导入更高版可能会报错,这个包在百度搜slf4j就能进入它的官网,很容易找到;

这个时候启动如果不报错,那成功一半了;接下来就是配置实体类了,比如一个商城系统要对订单建索引,实体类如(给出关键部分代码):

Java代码 复制代码  收藏代码
  1. @Entity  
  2. @Indexed(index="shopOrders")  
  3. public class ShopOrders  implements java.io.Serializable {  
  4.   
  5.   
  6.     // Fields      
  7.   
  8.      @DocumentId  
  9.      private String id;  
  10.      private Integer uid;  
  11.      @Field(index=Index.TOKENIZED,store=Store.YES)  
  12.      private String username;  
  13.      @Field(index=Index.UN_TOKENIZED,store=Store.YES)  
  14.      private Integer isDelete;  
@Entity
@Indexed(index="shopOrders")
public class ShopOrders  implements java.io.Serializable {


    // Fields    

     @DocumentId
     private String id;
     private Integer uid;
     @Field(index=Index.TOKENIZED,store=Store.YES)
     private String username;
     @Field(index=Index.UN_TOKENIZED,store=Store.YES)
     private Integer isDelete;



这个时候启动你会发现你指定的路径下已经有了一个shopOrders文件夹,如果这个时候去搜索是搜索不到的,还没有初始化数据;
以下是数据初始化和查询的代码:

Java代码 复制代码  收藏代码
  1. import java.util.Date;  
  2. import java.util.List;  
  3.   
  4. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  5. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  6. import org.apache.lucene.queryParser.QueryParser;  
  7. import org.apache.lucene.search.BooleanClause;  
  8. import org.apache.lucene.search.BooleanQuery;  
  9. import org.apache.lucene.search.Query;  
  10. import org.hibernate.CacheMode;  
  11. import org.hibernate.FlushMode;  
  12. import org.hibernate.ScrollMode;  
  13. import org.hibernate.ScrollableResults;  
  14. import org.hibernate.Session;  
  15. import org.hibernate.SessionFactory;  
  16. import org.hibernate.search.FullTextQuery;  
  17. import org.hibernate.search.FullTextSession;  
  18. import org.hibernate.search.Search;  
  19. import org.springframework.orm.hibernate3.LocalSessionFactoryBean;  
  20. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  21.   
  22. import com.china.fung.hibernate.pojo.shop.ShopOrders;  
  23.   
  24. public class Dao extends HibernateDaoSupport {  
  25.   
  26.     private static SessionFactory sessionFactory;  
  27.     private static Session session = null;  
  28.     private static LocalSessionFactoryBean factoryBean = null;  
  29.   
  30.     public void getMySession() throws Exception {  
  31.         sessionFactory = this.getHibernateTemplate().getSessionFactory();  
  32.         session = sessionFactory.openSession();  
  33.     }  
  34.   
  35.     public List search(String keyword) throws Exception {  
  36.         this.getMySession();  
  37.         BooleanQuery.setMaxClauseCount(100000);  
  38.         BooleanQuery booleanQuery = new BooleanQuery();  
  39.         StandardAnalyzer analyzer=new StandardAnalyzer();  
  40.         // 基本关键词搜索  
  41.         String[] searchFields = new String[] { "username" };//成员变量  
  42.         MultiFieldQueryParser queryParser = new MultiFieldQueryParser(  
  43.                 searchFields,analyzer);  
  44.         queryParser.setDefaultOperator(QueryParser.Operator.AND);  
  45.         Query query = queryParser.parse(keyword);  
  46.         booleanQuery.add(query,BooleanClause.Occur.MUST);  
  47.           
  48.         QueryParser parse=new QueryParser("isDelete",analyzer);  
  49.         Query query1=parse.parse("0");  
  50.         parse.setDefaultOperator(QueryParser.Operator.AND);  
  51.         booleanQuery.add(query1,BooleanClause.Occur.MUST);  
  52.   
  53.         FullTextSession fullSession = Search.getFullTextSession(session);  
  54.         FullTextQuery fullQuery = fullSession.createFullTextQuery(booleanQuery,  
  55.                 ShopOrders.class);  
  56.         int size = fullQuery.getResultSize();  
  57.         System.out.println("size:" + size);  
  58.           
  59.         return fullQuery.list();  
  60.     }  
  61.       
  62.      public void createIndexByHibernateSearch() throws Exception{  
  63.          this.getMySession();  
  64.           long startTime = new Date().getTime();  
  65.           int BATCH_SIZE = 1000;  
  66.           FullTextSession s = Search.getFullTextSession(session);  
  67.   
  68.           // Transaction tr = s.beginTransaction();  
  69.           s.setFlushMode(FlushMode.MANUAL);  
  70.           s.setCacheMode(CacheMode.IGNORE);  
  71.           ScrollableResults results = s.createQuery("from ShopOrders").setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);  
  72.           int index = 0;  
  73.           while (results.next()) {  
  74.            index++;  
  75.            s.index(results.get(0)); // index each element  
  76.            if (index % BATCH_SIZE == 0) {  
  77.             // s.flushToIndexes(); //apply changes to indexes  
  78.             s.clear(); // clear since the queue is processed  
  79.            }  
  80.           }  
  81.           s.clear();  
  82.           long endTime = new Date().getTime();  
  83.           logger.warn("建立Product索引 , 这花费了" + (endTime - startTime) + " 毫秒来把文档增加到索引里面去!");  
  84.           // tr.commit();  
  85.   
  86.          }  
  87.       
  88.   
  89. }  
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.china.fung.hibernate.pojo.shop.ShopOrders;

public class Dao extends HibernateDaoSupport {

	private static SessionFactory sessionFactory;
	private static Session session = null;
	private static LocalSessionFactoryBean factoryBean = null;

	public void getMySession() throws Exception {
		sessionFactory = this.getHibernateTemplate().getSessionFactory();
		session = sessionFactory.openSession();
	}

	public List search(String keyword) throws Exception {
		this.getMySession();
		BooleanQuery.setMaxClauseCount(100000);
		BooleanQuery booleanQuery = new BooleanQuery();
		StandardAnalyzer analyzer=new StandardAnalyzer();
		// 基本关键词搜索
		String[] searchFields = new String[] { "username" };//成员变量
		MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
				searchFields,analyzer);
		queryParser.setDefaultOperator(QueryParser.Operator.AND);
		Query query = queryParser.parse(keyword);
		booleanQuery.add(query,BooleanClause.Occur.MUST);
		
		QueryParser parse=new QueryParser("isDelete",analyzer);
		Query query1=parse.parse("0");
		parse.setDefaultOperator(QueryParser.Operator.AND);
		booleanQuery.add(query1,BooleanClause.Occur.MUST);

		FullTextSession fullSession = Search.getFullTextSession(session);
		FullTextQuery fullQuery = fullSession.createFullTextQuery(booleanQuery,
				ShopOrders.class);
		int size = fullQuery.getResultSize();
		System.out.println("size:" + size);
		
		return fullQuery.list();
	}
	
	 public void createIndexByHibernateSearch() throws Exception{
		 this.getMySession();
		  long startTime = new Date().getTime();
		  int BATCH_SIZE = 1000;
		  FullTextSession s = Search.getFullTextSession(session);

		  // Transaction tr = s.beginTransaction();
		  s.setFlushMode(FlushMode.MANUAL);
		  s.setCacheMode(CacheMode.IGNORE);
		  ScrollableResults results = s.createQuery("from ShopOrders").setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);
		  int index = 0;
		  while (results.next()) {
		   index++;
		   s.index(results.get(0)); // index each element
		   if (index % BATCH_SIZE == 0) {
		    // s.flushToIndexes(); //apply changes to indexes
		    s.clear(); // clear since the queue is processed
		   }
		  }
		  s.clear();
		  long endTime = new Date().getTime();
		  logger.warn("建立Product索引 , 这花费了" + (endTime - startTime) + " 毫秒来把文档增加到索引里面去!");
		  // tr.commit();

		 }
	

}



好了,到这基本就完事了,只需要在service里调用就行了,别忘了,先调用createIndexByHibernateSearch方法初始化(一次就行),再调用search方法搜索;

你可能感兴趣的:(hibernate search 例子)