1.1
TermQuery
只需要指定要搜索的域和要搜索的关键词就可以搜索。
//使用TermQuery查询
@Test
public void testTermQuery() throws Exception {
//以读的方式打开索引库
Directory directory = FSDirectory.open(Paths.get("D:\\LucentTest\\luceneIndex"));
//创建一个IndexReader
IndexReader indexReader = DirectoryReader.open(directory);
//创建一个IndexSearcher对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//创建一个查询对象
Query query = new TermQuery(new Term("content", "java"));
//执行查询
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("查询结果总数量:" + topDocs.totalHits);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//取document对象
Document document = indexSearcher.doc(scoreDoc.doc);
System.out.println(document.get("name"));
System.out.println(document.get("path"));
}
indexReader.close();
}
1.2
MatchAllDocsQuery
//匹配所有文档
@Test
public void testMatchAllDocsQuery() throws Exception {
//以读的方式打开索引库
Directory directory = FSDirectory.open(Paths.get("D:\\LucentTest\\luceneIndex"));
//创建一个IndexReader
IndexReader indexReader = DirectoryReader.open(directory);
//创建一个IndexSearcher对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//创建一查询对象
Query query = new MatchAllDocsQuery();
//执行查询
//执行查询
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("查询结果总数量:" + topDocs.totalHits);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//取document对象
Document document = indexSearcher.doc(scoreDoc.doc);
System.out.println(document.get("name"));
//System.out.println(document.get("content"));
System.out.println(document.get("path"));
System.out.println(document.get("size"));
}
indexSearcher.getIndexReader().close();
}
//不匹配所有文档
@Test
public void testMatchNoDocsQuery() throws Exception {
//以读的方式打开索引库
Directory directory = FSDirectory.open(Paths.get("D:\\LucentTest\\luceneIndex"));
//创建一个IndexReader
IndexReader indexReader = DirectoryReader.open(directory);
//创建一个IndexSearcher对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//创建一查询对象
Query query = new MatchNoDocsQuery();
//执行查询
//执行查询
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("查询结果总数量:" + topDocs.totalHits);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
//取document对象
Document document = indexSearcher.doc(scoreDoc.doc);
System.out.println(document.get("name"));
}
indexSearcher.getIndexReader().close();
}
下面是小编的微信转帐二维码,小编再次谢谢读者的支持,小编会更努力的
----请看下方↓↓↓↓↓↓↓
百度搜索 Drools从入门到精通:可下载开源全套Drools教程
深度Drools教程不段更新中:
更多Drools实战陆续发布中………
扫描下方二维码关注公众号 ↓↓↓↓↓↓↓↓↓↓