[lucene] 有什么好的方法删除索引?同时也能将文件从文件目录中彻底删除
JavaCrazyer
2010-03-24
有什么好的方法删除索引???同时也能将文件从文件目录中彻底删除。大致步骤能说下么
|
|
TonyLian
2010-03-26
建立索引的时候,给每一个Document弄一个Field存文件的路径+文件名,删除Document时,从Filed中取出文件名,用File类物理删除
|
|
hengstart
2010-03-28
Tonylian 能说的详细一点吧!最好有一些代码。
|
|
TonyLian
2010-03-31
/** * 删除某日期(含)以前收录的文件及索引 * * @param date * 日期 */ public void delete(Date date) { IndexWriter iwriter = null; IndexSearcher isearcher = null; Directory directory = null; try { long start = new Date().getTime(); //前期准备工作 File indexPath = new File(SystemProperties.getIndexPath()); directory = FSDirectory.open(indexPath); if (indexPath.list().length > 0) { // 已有以往索引 iwriter = new IndexWriter(directory, this.analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED); } else { // 首次建立索引,既然是删除,应该不可能是首次建立 iwriter = new IndexWriter(directory, this.analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED); } // 用ADDTIME做查询条件 Query query = new TermRangeQuery(Constants.FEILD_ADDTIME, DateUtil.getDateString(Constants.LOWER_DATE), DateUtil.getDateString(date), true, true); //实例化搜索器 isearcher = new IndexSearcher(directory); // 先确定有多少满足条件的Documents TopDocs topDocs = isearcher.search(query, 1); int total = topDocs.totalHits; if (total > 0) { // 然后再查出所有满足条件的Documents topDocs = isearcher.search(query, total); ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 遍历取得文件存储位置并删除 for (int i = 0; i < scoreDocs.length; i++) { Document targetDoc = isearcher.doc(scoreDocs[i].doc); String fileName = targetDoc.get(Constants.FEILD_SERVERNAME); String fullPath = SystemProperties.getUploadFilePath() + File.separator + fileName; File f = new File(fullPath); f.delete(); } // 删除索引中的Documents iwriter.deleteDocuments(query); } // 注意这一句非常重要,否则虽然已经删除,但Documents数和存储空间都未被释放! // 但使用此方法的前提是,磁盘剩余空间必须有已用索引空间的2倍 iwriter.optimize(); // 对索引进行优化 long end = new Date().getTime(); if (log.isDebugEnabled()) { log.debug("Delete " + topDocs.totalHits + " documents added befor " + DateUtil.getDateString(date) + ", in " + (end - start) + " milliseconds."); } } catch (Throwable t) { if (log.isErrorEnabled()) { log.error(t.getMessage()); } } finally { if (iwriter != null) { try { iwriter.close(); } catch (CorruptIndexException e) { log.error(e.getMessage()); } catch (AlreadyClosedException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } } if (directory != null) { try { directory.close(); } catch (IOException e) { log.error(e.getMessage()); } } } } |
|
TonyLian
2010-03-31
应美女的要求,贴出了我的代码,除了删除文件外,还有一些其他地方也值得参考,请认真读一下其中的注释。
|