关键代码
Formatter formatter = new SimpleHTMLFormatter("", ""); Scorer scorer = new QueryScorer(query); Highlighter titleHighlighter = new Highlighter(formatter, scorer); Highlighter contentHighlighter = new Highlighter(formatter, scorer); Fragmenter titleFragmenter = new SimpleFragmenter(6); Fragmenter contentFragmenter = new SimpleFragmenter(20); titleHighlighter.setTextFragmenter(titleFragmenter); contentHighlighter.setTextFragmenter(contentFragmenter); String titleValue = titleHighlighter.getBestFragment(LuceneUtils.getAnalyzer(), "title", document.get("title")); String contentValue = contentHighlighter.getBestFragment(LuceneUtils.getAnalyzer(), "content", document.get("content")); document.getField("title").setValue(titleValue); document.getField("content").setValue(contentValue);
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 staticvoid pagination(Page page,String field,String keyword,Class 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 list = page.getItems(); if(list == null){ list = new ArrayList (); page.setItems(list); } list.clear(); for(int i=startIndex;i void add(T t) throws Exception{ Document document = javabean2document(t); IndexWriter indexWriter = new IndexWriter(getDirectory(), getAnalyzer(), getMaxFieldLength()); indexWriter.addDocument(document); indexWriter.close(); } public static void addAll(List 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 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 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 List search(String field,String keyword,int topN,Class clazz) throws Exception{ List list = new ArrayList (); 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 void printList(List 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 document2javabean(Document document,Class 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; } }
Article.java
package com.rk.lucene.entity; public class Article { private Integer id; private String title;//标题 private String content;//内容 public Article() { } public Article(Integer id, String title, String content) { this.id = id; this.title = title; this.content = content; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "编号: " + id + "\n标题: " + title + "\n内容: " + content + "\n------------------------------------------------------------------\n"; } }
输出结果:
编号为1号的文章得分是0.32994816 编号为7号的文章得分是0.28870463 编号为4号的文章得分是0.23330858 编号为5号的文章得分是0.23330858 编号为2号的文章得分是0.20414501 编号为3号的文章得分是0.20414501 编号: 1 标题: 疾风之刃 内容: 《疾风之刃》是一款超动作3D动漫风网游 ------------------------------------------------------------------ 编号: 7 标题: 疾风知劲草 内容: 疾风知劲草,谓在猛烈的大风中,可看出什 ------------------------------------------------------------------ 编号: 4 标题: 八神疾风 内容: 八神疾风(CV:植田佳奈)是日本动漫 ------------------------------------------------------------------ 编号: 5 标题: 逝去的疾风 内容: 大战中飞得最快的日本飞机,恐怕要数“疾 ------------------------------------------------------------------ 编号: 2 标题: 月光疾风 内容: 月光疾风,日本动漫《火影忍者》中的人物 ------------------------------------------------------------------ 编号: 3 标题: 疾风航班中 内容: 《疾风航班》是一款优质的动作模拟游戏 ------------------------------------------------------------------