前言
本文我们来对Lucene具体如何进行数据的搜索,进行详细的介绍。
环境准备
我们直接使用在上一篇文章中的应用代码案例。
因为索引和存储两者是分开的,对于某一个字段我们可以建立索引,但是不存储,我们依然可以对此字段进行搜索,但是因为我们没有存储,所以我们搜索出来的结果中不显示此字段的内容。
本文为了结果的展示明显,我们将“desc“属性进行索引并且存储。
搜索结果TopDocs类
Lucene搜索结果可通过TopDocs遍历,TopDocs类提供了少量的属性,如下:
| 方法或属性 | 说明 |
|---|---|
| totalHits | 匹配搜索条件的总记录数 |
| scoreDocs | 顶部匹配记录 |
注意:
Search方法需要指定匹配记录数量n:search(query, n)
TopDocs.totalHits:是匹配索引库中所有记录的数量
TopDocs.scoreDocs:匹配相关度高的前边记录数组,scoreDocs的长度小于等于search方法指定的参
数n
方式一 使用Lucene提供的Query子类
公共测试类:
public void doSearch(Query query)throws Exception{
// 创建Directory 流对象
Directory directory = FSDirectory.open(Paths.get("D:/lucene/index"));
// 创建IndexReader
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(indexReader);
// 获取TopDocs
TopDocs topDocs = searcher.search(query,10);
System.out.println("查询索引总条数:" + topDocs.totalHits);
ScoreDoc[] docs = topDocs.scoreDocs;
// 解析结果集
for (ScoreDoc scoreDoc : docs){
int docID = scoreDoc.doc;
Document document = searcher.doc(docID);
System.out.println("docID:"+docID);
System.out.println("bookId:"+document.get("id"));
System.out.println("name:"+document.get("name"));

本文详细介绍了Lucene的搜索方式,包括使用TermQuery、BooleanQuery、PhraseQuery等Query子类进行精确、布尔和短语查询,以及使用QueryParser进行基础查询、范围查询和组合条件查询。通过示例代码展示了各种查询方法的用法和结果。
最低0.47元/天 解锁文章
504

被折叠的 条评论
为什么被折叠?



