1 package cn.itcast.h_filter; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.lucene.document.Document; 7 import org.apache.lucene.queryParser.MultiFieldQueryParser; 8 import org.apache.lucene.queryParser.QueryParser; 9 import org.apache.lucene.search.Filter; 10 import org.apache.lucene.search.IndexSearcher; 11 import org.apache.lucene.search.NumericRangeFilter; 12 import org.apache.lucene.search.Query; 13 import org.apache.lucene.search.Sort; 14 import org.apache.lucene.search.SortField; 15 import org.apache.lucene.search.TopDocs; 16 import org.apache.lucene.util.Version; 17 import org.junit.Test; 18 19 import cn.itcast._domain.Article; 20 import cn.itcast._util.ArticleDocumentUtils; 21 import cn.itcast._util.LuceneUtils; 22 23 public class TestApp { 24 25 // 搜索 26 @Test 27 public void testSearch() throws Exception { 28 // 准备查询条件 29 String queryString = "lucene"; 30 31 // 执行搜索 32 List<Article> list = new ArrayList<Article>(); 33 34 // 1,把查询字符串转为Query对象(从title和content中查询) 35 QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new String[] { "title", "content" }, LuceneUtils.getAnalyzer()); 36 Query query = queryParser.parse(queryString); 37 38 // 2,执行查询,得到中间结果 39 IndexSearcher indexSearcher = new IndexSearcher(LuceneUtils.getDirectory()); // 指定所用的索引库 40 // TopDocs topDocs = indexSearcher.search(query, 100); // 最多返回前n条结果 41 42 // ========================================================================================== 【创建高亮器】 43 // indexSearcher.search(query, n); 44 // indexSearcher.search(query, filter, n); 45 // indexSearcher.search(query, filter, n, sort); 46 47 Filter filter = NumericRangeFilter.newIntRange("id", 5, 15, false, true); // null表示没有过滤条件 选择 (5,15] 之间的过滤的数据,后面的boolean判断 括号开闭用处的 48 TopDocs topDocs = indexSearcher.search(query, filter, 100); 49 50 // ========================================================================================== 51 52 // 3,处理结果 53 for (int i = 0; i < topDocs.scoreDocs.length; i++) { 54 // 根据编号拿到Document数据 55 int docId = topDocs.scoreDocs[i].doc; // Document的内部编号 56 Document doc = indexSearcher.doc(docId); 57 // 把Document转为Article 58 Article article = ArticleDocumentUtils.documentToArticle(doc); 59 list.add(article); 60 } 61 indexSearcher.close(); 62 63 // 显示结果 64 System.out.println("总结果数:" + list.size()); 65 for (Article a : list) { 66 System.out.println("------------------------------"); 67 System.out.println("id = " + a.getId()); 68 System.out.println("title = " + a.getTitle()); 69 System.out.println("content = " + a.getContent()); 70 } 71 } 72 }