首页 > 代码库 > lucene 过滤结果
lucene 过滤结果
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 @Test27 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转为Article58 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。