Lucene笔记02-Lucene简介和搜索初步

本文通过示例代码详细介绍了使用Lucene进行文档搜索的方法,包括创建Directory、IndexReader和IndexSearcher,以及使用QueryParser进行搜索。同时,文章还讨论了在更新索引时可能遇到的不准确搜索结果问题,并提到了增量索引可能导致的后果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简单介绍Lucene的搜索

public void searcher() {
    try {
        // 创建Directory
        Directory directory = FSDirectory.open(new File("E:\\Lucene\\IndexLibrary"));
        // 创建IndexReader
        IndexReader indexReader = IndexReader.open(directory);
        // 根据IndexReader创建IndexSearcher
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        // 创建QueryParser,确定搜索文件的内容,第二个参数表示搜索的域
        QueryParser queryParser = new QueryParser(Version.LUCENE_35,"content",new StandardAnalyzer(Version.LUCENE_35));
        // 创建搜索的Query,表示搜索content域中包含Java的文档
        Query query = queryParser.parse("Java");
        // 根据IndexSearcher搜索并返回TopDocs
        TopDocs topDocs = indexSearcher.search(query,10);
        // 根据TopDocs获取ScoreDoc
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for(ScoreDoc scoreDoc : scoreDocs) {
            // 根据IndexSearcher和ScoreDoc对象获取具体的Document对象
            Document document = indexSearcher.doc(scoreDoc.doc);
            // 根据Document获取需要的值
            System.out.println(document.get("fileName")+" "+document.get("path"));
        }
        // 关闭IndexReader资源
        indexReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

运行之后,可以看到,在控制台打印出了文件名和路径,这就达到了搜索的目的。

二、遇到的问题

假如,我们再次创建索引,再次搜索,发现搜索结果多了,这肯定不符合实际情况啊,原文档没变,只是索引增加了,搜索结果却不准确了,这是因为前面创建索引的时候创建的是增量索引,所以会导致这个情况出现,后面我们会讲到解决方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值