04.索引的建立与维护
建立索引
public void createIndex() throws IOException {
//先指定索引库存放的位置
String dumpPath = "D:\\temp\\1110";
Directory directory = FSDirectory.open(new File(dumpPath));
//索引库存放在内存中
//Directory directory = new RAMDirectory();
//指定分析器
StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, standardAnalyzer);
//创建Indexwriter对象
IndexWriter indexWriter = new IndexWriter(directory, config);
//读取歌词并创建Document对象
File musicDir = new File("D:\\传智播客\\01.课程\\04.lucene\\01.参考资料\\歌词\\英文歌词");
for (File f:musicDir.listFiles()) {
//判断是否是文件
if (f.isFile()) {
//创建Document对象
Document document = new Document();
//创建域
//文件名称
Field fieldName = new TextField("filename", f.getName(), Store.YES);
//文件内容
String contentString = FileUtils.readFileToString(f);
Field fieldContent = new TextField("content", contentString, Store.YES);
//文件路径
Field fieldPath = new StoredField("path", f.getPath());
//文件 的大小
Field fieldSize = new LongField("size", FileUtils.sizeOf(f), Store.YES);
//把域添加到Document中
document.add(fieldName);
document.add(fieldContent);
document.add(fieldPath);
document.add(fieldSize);
//把Document写入索引库
indexWriter.addDocument(document);
}
}
//关闭indexwriter
indexWriter.close();
}
删除索引
删除所有索引
public void deleteAllIndex() throws IOException {
IndexWriter indexWriter = getIndexWriter();
indexWriter.deleteAll();
indexWriter.commit();
}
删除指定索引
public void deleteIndex() throws IOException {
IndexWriter indexWriter = getIndexWriter();
//创建一个查询
Query query = new TermQuery(new Term("filename", "张信哲"));
indexWriter.deleteDocuments(query);
indexWriter.commit();
}
更新索引(会替换文档)
// 索引目录
public void updateIndex( ) throws Exception{
Directory directory = FSDirectory.open(new File(indexFolder));
// 定义索引操作对象
IndexWriter indexWriter = new IndexWriter(directory,
new IndexWriterConfig(Version.LUCENE_4_10_3,
new StandardAnalyzer()));
// 创建更新文档
Document doc_update = new Document();
Field field_fileName = new TextField("fileName", "springmvc.txt",
Store.YES);
doc_update.add(field_fileName);
// 根据条件更新索引,将fileName等于“springmvc_test.txt”的更新为上边的文档
// 更新的机制 是先删除再添加,如果原根据fileName没有找到“springmvc_test.txt”,则添加新文档
indexWriter.updateDocument(new Term("fileName", "springmvc_test.txt"),
doc_update);
//提交
indexWriter.commit();
//关闭
indexWriter.close();
}