Hibernate provides Full-text indexing, which is great, and here's a brief introduction to its usage,
1. Introducing package dependencies in Pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactid>hibernate-search-orm </artifactId>
<version>${hibernate-search.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId> lucene-analyzers-smartcn</artifactid>
<version>${lucene.version}</version>
</ dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
< Artifactid>lucene-queryparser</artifactid>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-phonetic</artifactId>
<version>${lucene.version}</ Version>
</dependency>
Hibernate configuration Search Index save path
<bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean"
Destroy "> <property name=" dataSource "ref=" Poolingdatasource "/> <property" name= "Configlocation" > <value> classpath:hibernate.cfg.xml </value> </property> <property name= "Hibernateproper Ties "> <props> <prop key=" Hibernate.dialect ">${hibernate.dialect}</prop> <!- -Booleans can is easily used in expressions by declaring HQL query substitutions in Hibernate- -> <prop key= "hibernate.query.substitutions" >true ' Y ', false ' N ' </prop> <!--HTTP://EHCA Che.org/documentation/integrations/hibernate--> <!--HTTP://WWW.TUTORIALSPOINT.COM/HIBERNATE/HIBERNATE_CAC hing.htm--> <prop key= "Hibernate.cache.use_second_level_cache" >true</prop> <!--Org.hib Ernate.cache.ehcache.EhCaCheregionfactory--> <prop key= "Hibernate.cache.region.factory_class" >org.hibernate.cache.ehcache.ehcach Eregionfactory</prop> <!--hibernate only cache a single persisted object obtained using the load () method if you want to cache the use of FindAll (), list (), iterator (), Createc Riteria (), CreateQuery () and other methods to obtain the data result set, you need to set the Hibernate.cache.use_query_cache true--> <prop ke Y= "Hibernate.cache.use_query_cache" >true</prop> <prop key= "Net.sf.ehcache.configurationResourceName" >ehcache-hibernate.xml</prop> <!--hibernate Search index directory--> ***<prop key= "Hi
Bernate.search.default.indexBase ">indexes/</prop>*** </props> </property> </bean>
Add indexed Annotation to the classes that need to be searched, and then add @field Annotation to the fields that can be searched in the class, usually the enum field does not need analyzer for lexical analysis, and other fields are required. You do not need to store the actual data in index for situations where you do not need to projection (return a partial field). You can define different lexical parsers through analyzerdef and the special word filter
for
@Indexed @AnalyzerDef (name= "Entopicanalyzer", charfilters={@CharFilterDef (factory=htmlstripcharfilterfact Ory.class)}, tokenizer= @TokenizerDef (factory=standardtokenizerfactory.class), filters={@TokenFilterDef (Factory=standardfilterfactory.class), @TokenFilterDef (Factory=stopfilterfactory.class), @TokenFilterDef (facto Ry=phoneticfilterfactory.class, params = {@Parameter (name= "encoder", value= "Doublemetaphone")} ), @TokenFilterDef (factory=snowballporterfilterfactory.class, params = {@Parameter (name=) language ", value=" 中文版 ")}) public class Topic {... @Field (Index=index.yes, Analyze=analyze.yes, S
tore=store.no) @Analyzer (definition = "entopicanalyzer") private String title; ... @Field (Index=index.yes, Analyze=analyze.yes, store=store.no) @Analyzer (definition = "entopicanalyzer") privat
e String content;
... @Enumerated (enumtype.string) @Field (Index=index.yes, analyze=analyze.no, store=store.no, bridge= @FieldBridge (impl=enumbridge.class)) private
Topicstatus status;
...
}
Create index on existing data through code
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). Close ();
Create query Fulltextsession, get results by query criteria
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 one test, the value object was modified, the new index was added, the RebuildIndex was forgotten, and the result of the unit test was no problem and the build environment went wrong.
2. Search is not very strong, such as search test, contains the results of testing may not be able to search out
Chinese lexical analysis
Hibernate search at the bottom of the use of Lucene, so lucene can use Chinese participle, hibernate search can be used to support Chinese lexical analysis, more commonly used lexical analyzer including Paoding,ikanalyzer, Mmseg4j and so on. Specific can be referred to the analysis of the recent analysis of participle. Hibernate search the default word breaker is Org.apache.lucene.analysis.standard.StandardAnalyzer, Chinese word segmentation, obviously not in line with our needs.
Here is how to configure the Chinese word segmentation in the hibernate, the choice is Lucene's own Chinese participle-. Use can be done in 3 ways, one is to set the lexical analysis method in the Hibernate configuration file, the other is to define the participle method in each class that needs to be searched, and the last one is to configure a single field. Here are the first 2 ways to configure.
Hibernate configuration mode:
<property name= "Hibernate.search.analyzer" > org.apache.lucene.analysis.cn.smart.smartchineseanalyzer</ Property>
The search class is configured with Chinese participle:
@Indexed
@Analyzer (impl=smartchineseanalyzer.class)
Also need to introduce dependent package dependencies in Maven
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId> lucene-analyzers-smartcn</artifactid>
<version>${lucene.version}</version>
</ Dependency>
Multi-condition Query
Hibernate search can be multiple conditions to achieve multiple conditional query, here a simple introduction to the practice of multiple conditional query.
If it's just a single condition query, then this query can be simple
Lucenequery = Querybuilder.keyword (). Onfields ("title", "Content"). Matching (Query.getkeyword ()). CreateQuery ()
If it is a multiple condition and query, then you need to use the must join, if it is a multiple conditions or query, you need to use the should join, here is an example of must join
Must true
mustjunction term = querybuilder.bool (). Must (Querybuilder.keyword ()
. Onfields ("title", "Content ") . Matching (Query.getkeyword ()). CreateQuery ());
Must false
Term.must (Querybuilder.keyword ()
. Onfield ("status") . Matching (Query.getexcludestatus () ). CreateQuery ()). not ();
Complete Example:
Private FullTextQuery findbykeywordquery (topicquery query) {fulltextsession fulltextsession = Search. getful
Ltextsession (GetSession ());
QueryBuilder QueryBuilder = Fulltextsession.getsearchfactory (). Buildquerybuilder (). forentity (Topic.class). get ();
Org.apache.lucene.search.Query lucenequery = null;
if (null = = Query.getstatus () && null = = Query.getusername () && null = = Query.getexcludestatus ()) {
Lucenequery = Querybuilder.keyword ()//. Wildcard (). Onfields ("title", "Content"). Matching (Query.getkeyword ())
. Matching ("*" + query.getkeyword () + "*"). CreateQuery ();
if (log.isdebugenabled ()) {log.debug ("Create clean keyword search query:" + lucenequery.tostring ()); } else {Mustjunction term = Querybuilder.bool (). Must (Querybuilder.keyword (). Onfields ("title", "Con
Tent "). Matching (Query.getkeyword ()). CreateQuery ());
if (null!= query.getstatus ()) { Term.must (Querybuilder.keyword ()//. Wildcard (). Onfield ("status"). Matching (
Query.getstatus ()). CreateQuery ());
} if (null!= query.getexcludestatus ()) {term.must () Querybuilder.keyword (). Onfield ("status")
. Matching (Query.getexcludestatus ()). CreateQuery ()). not ();
} if (null!= query.getusername ()) {term.must () Querybuilder.keyword ()//. Wildcard () . Onfield ("Owner.username"). Ignorefieldbridge (). Matching (Query.getusername ()). CreateQuery
());
} lucenequery =term.createquery ();
if (log.isdebugenabled ()) {Log.debug ("create complicated keyword search query:" + lucenequery.tostring ()); }//Booleanquery fulltextquery hibernatequery = Fulltextsession.createfulltextquery (Lucenequery, T
Opic.class);
return hibernatequery;
}