PS:这是通用代码,下面的子类查询调用到的时候就不再写这部分的具体的实现过程了
/** * 构造IndexSearcher对象 * * @return * @throws Exception */ private IndexSearcher getIndexSearcher() throws Exception { /*创建一个Directory对象,指定索引库的位置*/ Directory directory = FSDirectory.open(new File("E:\\zhanghaoBF\\luceneSolr\\indexLibrary").toPath());//磁盘(硬盘)上的路径 /*创建一个IndexReader(索引读取)对象*/ IndexReader indexReader = DirectoryReader.open(directory);//打开索引库(此对象为流对象) /*创建一个IndexSearcher(索引搜索)对象*/ IndexSearcher indexSearcher = new IndexSearcher(indexReader); return indexSearcher;//索引对象 } /** * 执行查询并打印结果 * * @param query * @param indexSearcher * @throws Exception */ private void printResult(Query query, IndexSearcher indexSearcher) throws Exception { /*执行查询*/ TopDocs topDocs = indexSearcher.search(query, 10);//根据query搜索,返回评分最高的10条 /*返回查询结果,遍历查询结果并输出*/ ScoreDoc[] scoreDocs = topDocs.scoreDocs;//PS:注意这里返回的是文档id的数组 for (ScoreDoc scoreDoc : scoreDocs) { int docId = scoreDoc.doc;//文档ID Document document = indexSearcher.doc(docId);//对应的文档 String fileName = document.get("fileName");//文件名称 System.out.println(fileName); String fileSize = document.get("fileSize");//文件大小 System.out.println(fileSize); String filePath = document.get("filePath");//文件路径 System.out.println(filePath); System.out.println("----------华丽的分割线----------"); } }