Hibernate search 1

Source: Internet
Author: User

Hibernate search 1

Hibernate provides the full-text index function, which is very good. Here we will briefly introduce its usage,
1. Introduce the package dependency in pom. xml


             
   
    org.hibernate
              hibernate-search-orm           
   
    ${hibernate-search.version}
           
          
              
   
    org.apache.lucene
               lucene-analyzers-smartcn            
   
    ${lucene.version}
           
          
              
   
    org.apache.lucene
               lucene-queryparser            
   
    ${lucene.version}
           
          
              
   
    org.apache.lucene
               lucene-analyzers-phonetic            
   
    ${lucene.version}
           
  
Hibernate configures the search index storage path
 
          
           
                
     
      
Classpath: hibernate. cfg. xml
             
            
                
                     
      
        $ {Hibernate. dialect}
                      
                      
      
        True 'y', false 'n'
                      
                      
                      
      
        True
                      
                      
      
        Org. hibernate. cache. ehcache. EhCacheRegionFactory
                      
                      
      
        True
                      
      
        Ehcache-hibernate.xml
                      
      ***
      
        Indexes/
      ***
             
        
   
   
Add Indexed Annotation to the class to be searched, and then add @ Field Annotation to the fields that can be searched in the class. Generally, the Enum Field does not require Analyzer to perform lexical analysis, while other fields require, if Projection is not required (some fields are returned), actual data does not need to be stored in the index. AnalyzerDef can be used to define different lexical analyzers and special word filters.
@Indexed@AnalyzerDef(        name=enTopicAnalyzer,        charFilters={            @CharFilterDef(factory=HTMLStripCharFilterFactory.class)        },        tokenizer=@TokenizerDef(factory=StandardTokenizerFactory.class),        filters={            @TokenFilterDef(factory=StandardFilterFactory.class),            @TokenFilterDef(factory=StopFilterFactory.class),            @TokenFilterDef(factory=PhoneticFilterFactory.class,                params = {                    @Parameter(name=encoder, value=DoubleMetaphone)                }),            @TokenFilterDef(factory=SnowballPorterFilterFactory.class,                params = {                    @Parameter(name=language, value=English)                })            }    )public class Topic {    ......    @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)    @Analyzer(definition = enTopicAnalyzer)    private String title;    ......    @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)    @Analyzer(definition = enTopicAnalyzer)    private String content;    ......        @Enumerated(EnumType.STRING)    @Field(index=Index.YES, analyze=Analyze.NO, store=Store.NO, bridge=@FieldBridge(impl=EnumBridge.class))    private TopicStatus status;    ...    }
Use the code to create an index for existing data
ApplicationContext context = new ClassPathXmlApplicationContext(spring-resources.xml);        SessionFactory sessionFactory = (SessionFactory) context.getBean(sessionFactory);        Session sess = sessionFactory.openSession();        FullTextSession fullTextSession = Search.getFullTextSession(sess);        try {            fullTextSession.createIndexer().startAndWait();        } catch (InterruptedException e) {             LOG.error(e.getMessage(), e);        } finally {            fullTextSession.close();        }        ((AbstractApplicationContext)context).close();
Create a query fulltextsession and obtain the result according to the query conditions.
 FullTextSession fullTextSession = Search                .getFullTextSession(getSession());        QueryBuilder queryBuilder = fullTextSession.getSearchFactory()                .buildQueryBuilder().forEntity(Show.class).get();        org.apache.lucene.search.Query luceneQuery = null;            luceneQuery = queryBuilder.keyword()// .wildcard()                    .onFields(title, content).matching(query.getKeyword())                    // .matching(* + query.getKeyword() + *)                    .createQuery();        FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(                luceneQuery, Show.class);        return hibernateQuery.list();

Note:
1. During a test, the value object was modified, a new index was added, and rebuildIndex was forgotten. The result of the unit test was no problem, and an error occurred when generating the environment.
2. The search is not very powerful. For example, the search test may fail to contain the test results.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.