lucene&solr查询索引实例

1.实现步骤:

 2.代码

    // 搜索索引
    @Test
    public void testSearch() throws Exception {
        // 第一步:创建一个Directory对象,也就是索引库存放的位置。
        Directory directory = FSDirectory.open(new File("D:\temp\index"));// 磁盘
        // 第二步:创建一个indexReader对象,需要指定Directory对象。
        IndexReader indexReader = DirectoryReader.open(directory);
        // 第三步:创建一个indexsearcher对象,需要指定IndexReader对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        // 第四步:创建一个TermQuery对象,指定查询的域和查询的关键词。
        Query query = new TermQuery(new Term("fileName", "lucene"));
        // 第五步:执行查询。TopDocs对象表示查询到的多条文档的信息
        TopDocs topDocs = indexSearcher.search(query, 10);
        // 第六步:返回查询结果。遍历查询结果并输出。
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int doc = scoreDoc.doc;
            Document document = indexSearcher.doc(doc);
            // 文件名称
            String fileName = document.get("fileName");
            System.out.println(fileName);
            // 文件内容
            String fileContent = document.get("fileContent");
            System.out.println(fileContent);
            // 文件大小
            String fileSize = document.get("fileSize");
            System.out.println(fileSize);
            // 文件路径
            String filePath = document.get("filePath");
            System.out.println(filePath);
            System.out.println("------------");
        }
        // 第七步:关闭IndexReader对象
        indexReader.close();

    }
原文地址:https://www.cnblogs.com/ibcdwx/p/13525830.html