package org.example;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import java.nio.file.Paths;
public class IndexReaderSearchExample {
public static void main(String[] args) throws Exception {
String indexPath = "D:/lucene9_index/test1";
String field = "content";
String keyword = "编程";
// 1. 打开索引
DirectoryReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath)));
// 2. 遍历所有段(LeafReaderContext)
for (LeafReaderContext leafCtx : reader.leaves()) {
LeafReader leafReader = leafCtx.reader();
// 3. 获取字段的倒排表
Terms terms = leafReader.terms(field);
if (terms == null) continue;
TermsEnum termsEnum = terms.iterator();
BytesRef termBytes = new BytesRef(keyword);
// 4. 查找关键词是否存在
if (termsEnum.seekExact(termBytes)) {
PostingsEnum postings = termsEnum.postings(null, PostingsEnum.ALL);
// 5. 遍历匹配的文档
while (postings.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
int docId = postings.docID();
int globalDocId = docId + leafCtx.docBase; // 全局 docId(可选)
Document doc = leafReader.document(docId);
System.out.println("全局 DocId: " + globalDocId);
System.out.println("路径: " + doc.get("path"));
// System.out.println("内容: " + doc.get("content"));
System.out.println("----");
}
}
}
reader.close();
}
}
【lucene】仅使用IndexReader来实现搜索功能代码案例
最新推荐文章于 2025-11-20 11:01:01 发布

462

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



