日期:2014-05-18 浏览次数:20854 次
public class SearchServiceImpl implements SearchService{ private String index_Path; private final int HITS_PER_PAGE=10; public List search(String q,int start) throws IOException { try { List<Content> searchList = new ArrayList<Content>(); IndexSearcher searcher = new IndexSearcher(index_Path); Analyzer analyzer = new MMAnalyzer(2); //布爾查找 BooleanQuery booleanQuery = new BooleanQuery(); QueryParser parser = new QueryParser("Content",analyzer); Query query = parser.parse(q); booleanQuery.add(query,Occur.SHOULD); QueryParser parser2 = new QueryParser("Title",analyzer); Query query2 = parser2.parse(q); booleanQuery.add(query2,Occur.SHOULD); //排序 //Sort sort = new Sort(); //SortField sf = new SortField("ContentId",SortField.INT, true);//降序,false為升序 //sort.setSort(sf); //Hits hits = searcher.search(booleanQuery , sort);//按上面的設置來排序 long timeStart = System.currentTimeMillis(); Hits hits = searcher.search(booleanQuery , Sort.RELEVANCE);//按得分來排序 SimpleHTMLFormatter sHtmlF = new SimpleHTMLFormatter("<font color=#c60a00>","</font>"); Highlighter highlighter = new Highlighter(sHtmlF,new QueryScorer(booleanQuery)); highlighter.setTextFragmenter(new SimpleFragmenter(40)); long timeUsed = System.currentTimeMillis() - timeStart; //logger.info("get resultset successfully! (" + timeUsed // + " milliseconds used)" // ); int end =0; if((start ==0 ) || (start==1)){ start = 0; end = Math.min(hits.length(), HITS_PER_PAGE); }else{ int page = start; start = (start-1)*HITS_PER_PAGE; end = Math.min(hits.length(), page*HITS_PER_PAGE); } //for (; start < hits.length(); start += HITS_PER_PAGE ) { //int end = Math.min(hits.length(), start + HITS_PER_PAGE); for (int i = start; i < end; i++) { Content bean = new Content(); //System.out.print("score=" + hits.score(i) + "\t"); bean.setDocsID(hits.id(i)); bean.setHits_per_page(HITS_PER_PAGE); bean.setTotal(hits.length()); bean.setScore(String.valueOf(hits.score(i))); bean.setTimeUsed(String.valueOf(timeUsed)); //System.out.println(bean.getTotal()); Enumeration e = hits.doc(i).fields(); while (e.hasMoreElements()) {