黑马程序员技术交流社区

标题: 【郑州校区】查询索引数据的代码实现 [打印本页]

作者: 我是楠楠    时间: 2019-4-18 09:47
标题: 【郑州校区】查询索引数据的代码实现
【郑州校区】查询索引数据的代码实现

代码实现
[AppleScript] 纯文本查看 复制代码
@Test
        public void testSearcher() throws IOException, ParseException{
               
                // 初始化索引库对象
                Directory directory = FSDirectory.open(new File("C:\\tmp\\index"));
               
                // 索引读取工具
                IndexReader indexReader = DirectoryReader.open(directory);
                // 索引搜索对象
                IndexSearcher indexSearcher = new IndexSearcher(indexReader);
               
                // 创建查询解析器对象
                QueryParser parser = new QueryParser("title", new IKAnalyzer());
                // 创建查询对象
                Query query = parser.parse("谷歌");
                // 执行搜索操作,返回值topDocs包含命中数,得分文档
                TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);
                // 打印命中数
                System.out.println("一共命中:"+topDocs.totalHits+"条数据");
                // 获得得分文档数组对象,得分文档对象包含得分和文档编号
                ScoreDoc[] scoreDocs = topDocs.scoreDocs;
                for (ScoreDoc scoreDoc : scoreDocs) {
                        System.out.println("得分:"+scoreDoc.score);
                        // 文档的编号
                        int doc = scoreDoc.doc;
                        System.out.println("编号:"+doc);
                        // 获取文档对象,通过索引读取工具
                        Document document = indexReader.document(doc);
                        System.out.println("id:"+document.get("id"));
                        System.out.println("title:"+document.get("title"));
                }
        }

传智播客·黑马程序员郑州校区地址
河南省郑州市 高新区长椿路11号大学科技园(西区)东门8号楼三层
联系电话 0371-56061160/61/62
来校路线  地铁一号线梧桐街站A口出






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2