關(guān)鍵問(wèn)題是返回到頁(yè)面的是一個(gè)個(gè)對(duì)象。如果把搜索的結(jié)果中的關(guān)鍵字設(shè)置為高亮,謝謝
InfoPushController:
Page page = infoPushManager.searchKeyword(keyword,request.getParameter("pageNo"),best,category);
List list = new ArrayList();
if(page != null)
list = (List)page.getResult();
mav.addObject("infoPushs", list);
//關(guān)鍵問(wèn)題是返回到頁(yè)面的是一個(gè)個(gè)對(duì)象。
InfoPushManager 里的2個(gè)方法:
public Page searchKeyword(String keyword,String pageNoStr,int best,String category)
{
int pageNo = 1;
if (StringUtils.isNotEmpty(pageNoStr))
pageNo = Integer.parseInt(pageNoStr);
try{
IndexSearcher searcher = new IndexSearcher(IndexReader.open(Constants.INDEX_STORE_PATH));
String bestStr = String.valueOf(best);
/***** 一個(gè)關(guān)鍵字,在兩個(gè)字段中查詢 *****/
/*
* 1.BooleanClause.Occur[]的三種類型:
* MUST : + and
* MUST_NOT : - not
* SHOULD : or
* 2.下面查詢的意思是:content中必須包含該關(guān)鍵字,而title有沒(méi)有都無(wú)所謂
* 3.下面的這個(gè)查詢中,Occur[]的長(zhǎng)度必須和Fields[]的長(zhǎng)度一致。每個(gè)限制條件對(duì)應(yīng)一個(gè)字段
*/
org.apache.lucene.search.Query query = null;
if(best == 1)
{
BooleanClause.Occur[] flags = new BooleanClause.Occur[]{BooleanClause.Occur.MUST,BooleanClause.Occur.MUST,BooleanClause.Occur.MUST};
query = MultiFieldQueryParser.parse(new String[]{keyword,category,bestStr},new String[]{"contents","category","best"},flags,new StandardAnalyzer());
}
else
{
BooleanClause.Occur[] flags = new BooleanClause.Occur[]{BooleanClause.Occur.MUST,BooleanClause.Occur.MUST};
query = MultiFieldQueryParser.parse(new String[]{keyword,category},new String[]{"contents","category"},flags,new StandardAnalyzer());
}
// org.apache.lucene.search.Query query = QueryParser.parse(keyword, "contents",new StandardAnalyzer());
Hits hits = searcher.search(query);
//高亮顯示設(shè)置
SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<red>","</red>");
Highlighter highlighter = new Highlighter(simpleHTMLFormatter,new QueryScorer(query));
highlighter.setTextFragmenter(new SimpleFragmenter(10));//這個(gè)100是指定關(guān)鍵字字符串的context的長(zhǎng)度,你可以自己設(shè)定,因?yàn)椴豢赡芊祷卣膬?nèi)容
return pagedQueryLucene(pageNo, PageContants.SEARCH_AJAX_PAGES, hits);
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
public Page pagedQueryLucene(int pageNo, int pageSize,Hits h) {
long totalCount = 0;
int startIndex = 0;
List list = new ArrayList();
if (h.length() == 0) {
System.out.println("have no data !");
}
else
{
totalCount = h.length();
if (totalCount < 1) return new Page();
// 實(shí)際查詢返回分頁(yè)對(duì)象
startIndex = Page.getStartOfPage(pageNo, pageSize);
//long step = totalCount > pageSize ? pageSize : totalCount;
long endIndex = startIndex + Page.stepDataOfPage(pageSize, totalCount, pageNo);
for (int i = startIndex; i < endIndex; i++) {
try {
Document doc = h.doc(i);
String id = doc.get("id");
InfoPush infoPush = dao.get(id);
list.add(infoPush);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return new Page(startIndex, totalCount, pageSize, list);
}
聯(lián)系客服