【lucene】仅使用IndexReader来实现搜索功能代码案例

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值