I am working on an interactive Q & A platform, similar to Baidu knows, so intra-site search is particularly crucial. I use Lucene-based hibernate search to implement intra-site search.
The versions I use are hibernate search4.1 and javase3.5.
The search requirement of this Q & A platform is to find the questions you are interested in. Therefore, you can search the title and content in the question table, that is, the title and content.
The following is the core code:
Public List
Search (String queryString) throws IOException {Session session = sessionFactory. openSession (); FullTextSession fullTextSession = Search. getFullTextSession (session); QueryBuilder queryBuilder = fullTextSession. getSearchFactory (). buildQueryBuilder (). forEntity (Question. class ). get (); // modify the System field to be queried here. out. println (queryString); Query effecequery = queryBuilder. keyword (). onFields ("title", "content "). matching (queryString ). createQuery (); org. hibernate. query fullTextQuery = fullTextSession. createFullTextQuery (effecequery, Question. class); List
RsList = fullTextQuery. list (); // the code for the search function is shown above. The code for highlighting the keyword in the result set is SimpleHTMLFormatter formatter = new SimpleHTMLFormatter ("",""); queryScorer queryScorer = new QueryScorer (luceneQuery); Highlighter highlighter = new Highlighter (formatter, queryScorer); Analyzer analyzer = new ChineseAnalyzer (); String [] fieldNames = {"title ", "content"}; for (Question q: rsList) {for (String fieldName: fieldNames) {// use reflection to obtain a specific Object fieldValue = ReflectionUtils. invokeMethod (BeanUtils. getPropertyDescriptor (Question. class, fieldName ). getReadMethod (), q); // ReflectionUtils. getField (ReflectionUtils. findField (searchResultClass, fieldName), e); String hightLightFieldValue = null; if (fieldValue instanceof String) {try {// obtain the highlighted keyword hightLightFieldValue = highlighter. getBestFragment (analyzer, fieldName, ObjectUtils. toString (fie LdValue, null);} catch (IOException e1) {e1.printStackTrace ();} catch (InvalidTokenOffsetsException e1) {e1.printStackTrace ();} // this judgment is critical, otherwise, if there are no keywords in the title or content, the problem will not be displayed. If (hightLightFieldValue! = Null) {// use the keyword in the reflection setting result set to highlight ReflectionUtils. invokeMethod (BeanUtils. getPropertyDescriptor (Question. class, fieldName ). getWriteMethod (), q, hightLightFieldValue); // setField (ReflectionUtils. findField (searchResultClass, fieldName), e, hightLightFieldValue) ;}}} fullTextSession. close (); return rsList ;}
The test is successful and the effect is good.