Lucene系列:(7)搜尋索引鍵高亮

來源:互聯網
上載者:User

標籤:lucene


在搜尋結果中,將與關健字相同的字元用紅色顯示

TestHighlighter.java

package com.rk.lucene.d_highlighter;import java.util.ArrayList;import java.util.List;import org.apache.lucene.document.Document;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.search.highlight.Formatter;import org.apache.lucene.search.highlight.Highlighter;import org.apache.lucene.search.highlight.QueryScorer;import org.apache.lucene.search.highlight.Scorer;import org.apache.lucene.search.highlight.SimpleHTMLFormatter;import org.junit.Test;import com.rk.lucene.entity.Article;import com.rk.lucene.utils.LuceneUtils;public class TestHighlighter {@Testpublic void testAdd() throws Exception{Article article = new Article(1,"你好","世界你好,Hello World");Document document = LuceneUtils.javabean2document(article);IndexWriter indexWriter = new IndexWriter(LuceneUtils.getDirectory(),LuceneUtils.getAnalyzer(),LuceneUtils.getMaxFieldLength());indexWriter.addDocument(document);indexWriter.close();}@Testpublic void testSearch() throws Exception{List<Article> list = new ArrayList<Article>();String keyword = "你好";QueryParser queryParser = new QueryParser(LuceneUtils.getVersion(), "content", LuceneUtils.getAnalyzer());Query query = queryParser.parse(keyword);IndexSearcher indexSearcher = new IndexSearcher(LuceneUtils.getDirectory());TopDocs topDocs = indexSearcher.search(query, 10);//以下代碼對內容中含有關鍵字的字串高亮顯示//格式對象Formatter formatter = new SimpleHTMLFormatter("<font color=‘red‘>", "</font>");//關鍵字對象Scorer scorer = new QueryScorer(query);//高亮對象Highlighter highlighter = new Highlighter(formatter, scorer);for(int i=0;i<topDocs.scoreDocs.length;i++){ScoreDoc scoreDoc = topDocs.scoreDocs[i];int docIndex = scoreDoc.doc;//關鍵字沒有高亮Document document = indexSearcher.doc(docIndex);//關鍵字高亮String titleHighlighter = highlighter.getBestFragment(LuceneUtils.getAnalyzer(), "title", document.get("title"));String contentHighlighter = highlighter.getBestFragment(LuceneUtils.getAnalyzer(), "content", document.get("content"));//將高亮後的結果再次封裝到document對象中document.getField("title").setValue(titleHighlighter);document.getField("content").setValue(contentHighlighter);Article article = LuceneUtils.document2javabean(document, Article.class);list.add(article);}for(Article article : list){System.out.println(article);}}}


LuceneUtils.java

package com.rk.lucene.utils;import java.io.File;import java.io.IOException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import org.apache.commons.beanutils.BeanUtils;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.Index;import org.apache.lucene.document.Field.Store;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.index.IndexWriter.MaxFieldLength;import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;import com.rk.lucene.entity.Page;public class LuceneUtils {private static Directory directory;private static Version version;private static Analyzer analyzer;private static MaxFieldLength maxFieldLength;private static final String LUCENE_DIRECTORY= "D:/rk/indexDB";static{try {directory = FSDirectory.open(new File(LUCENE_DIRECTORY));version = Version.LUCENE_30;analyzer = new StandardAnalyzer(version);maxFieldLength = MaxFieldLength.LIMITED;} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}//不讓外部new當前協助類的對象private LuceneUtils(){}public static <T> void pagination(Page<T> page,String field,String keyword,Class<T> clazz) throws Exception{QueryParser queryParser = new QueryParser(getVersion(), field, getAnalyzer()); Query query = queryParser.parse(keyword);IndexSearcher indexSearcher = new IndexSearcher(getDirectory());TopDocs topDocs = indexSearcher.search(query, 200);int totalHits = topDocs.totalHits;int curPage = page.getCurPage();int pageSize = page.getPageSize();int quotient = totalHits / pageSize;int remainder = totalHits % pageSize;int totalPages = remainder==0 ? quotient : quotient+1;int startIndex = (curPage-1) * pageSize;int stopIndex = Math.min(startIndex + pageSize, totalHits);List<T> list = page.getItems();if(list == null){list = new ArrayList<T>();page.setItems(list);}list.clear();for(int i=startIndex;i<stopIndex;i++){ScoreDoc scoreDoc = topDocs.scoreDocs[i];int docIndex = scoreDoc.doc;Document document = indexSearcher.doc(docIndex);T t = document2javabean(document, clazz);list.add(t);}page.setTotalPages(totalPages);page.setTotalItems(totalHits);indexSearcher.close();}public static <T> void add(T t) throws Exception{Document document = javabean2document(t);IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength());indexWriter.addDocument(document);indexWriter.close();}public static <T> void addAll(List<T> list) throws Exception{IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength());for(T t : list){Document doc = javabean2document(t);indexWriter.addDocument(doc);}indexWriter.close();}public static <T> void update(String field,String value,T t) throws Exception{Document document = javabean2document(t);IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength());indexWriter.updateDocument(new Term(field,value), document);indexWriter.close();}public static <T> void delete(String field,String value) throws Exception{IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength());indexWriter.deleteDocuments(new Term(field,value));indexWriter.close();}/** * 刪除所有記錄 */public static void deleteAll() throws Exception {IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength());indexWriter.deleteAll();indexWriter.close();}/** * 根據關鍵字進行搜尋 */public static <T> List<T> search(String field,String keyword,int topN,Class<T> clazz) throws Exception{List<T> list = new ArrayList<T>();QueryParser queryParser = new QueryParser(getVersion(), field, getAnalyzer());Query query = queryParser.parse(keyword);IndexSearcher indexSearcher = new IndexSearcher(getDirectory());TopDocs topDocs = indexSearcher.search(query, topN);for(int i=0;i<topDocs.scoreDocs.length;i++){ScoreDoc scoreDoc = topDocs.scoreDocs[i];int docIndex = scoreDoc.doc;System.out.println("文檔索引號" + docIndex + ",文檔得分:" + scoreDoc.score);Document document = indexSearcher.doc(docIndex);T entity = (T) document2javabean(document, clazz);list.add(entity);}indexSearcher.close();return list;}/** * 列印List */public static <T> void printList(List<T> list){if(list != null && list.size()>0){for(T t : list){System.out.println(t);}}}//將JavaBean轉成Document對象public static Document javabean2document(Object obj) throws Exception{//建立Document對象Document document = new Document();//擷取obj引用的對象位元組碼Class clazz = obj.getClass();//通過對象位元組碼擷取私人的屬性java.lang.reflect.Field[] reflectFields = clazz.getDeclaredFields();//迭代for(java.lang.reflect.Field reflectField : reflectFields){//反射reflectField.setAccessible(true);//擷取欄位名String name = reflectField.getName();//擷取欄位值String value = reflectField.get(obj).toString();//加入到Document對象中去,這時javabean的屬性與document對象的屬性相同document.add(new Field(name, value, Store.YES, Index.ANALYZED));}//返回document對象return document;}//將Document對象轉換成JavaBean對象public static <T> T document2javabean(Document document,Class<T> clazz) throws Exception{T obj = clazz.newInstance();java.lang.reflect.Field[] reflectFields = clazz.getDeclaredFields();for(java.lang.reflect.Field reflectField : reflectFields){reflectField.setAccessible(true);String name = reflectField.getName();String value = document.get(name);BeanUtils.setProperty(obj, name, value);}return obj;}public static Directory getDirectory() {return directory;}public static void setDirectory(Directory directory) {LuceneUtils.directory = directory;}public static Version getVersion() {return version;}public static void setVersion(Version version) {LuceneUtils.version = version;}public static Analyzer getAnalyzer() {return analyzer;}public static void setAnalyzer(Analyzer analyzer) {LuceneUtils.analyzer = analyzer;}public static MaxFieldLength getMaxFieldLength() {return maxFieldLength;}public static void setMaxFieldLength(MaxFieldLength maxFieldLength) {LuceneUtils.maxFieldLength = maxFieldLength;}}





Lucene系列:(7)搜尋索引鍵高亮

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.