Lucene索引维护(四)

3/8/2017来源:ASP.NET技巧人气:2805

一、索引库的添加

//添加索引
	@Test
	public void addDocument() throws Exception {
		//索引库存放路径
		Directory directory = FSDirectory.open(new File("D:\\temp\\0108\\index"));
		
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new IKAnalyzer());
		//创建一个indexwriter对象
		IndexWriter indexWriter = new IndexWriter(directory, config);
		//创建一个Document对象
		Document document = new Document();
		//向document对象中添加域。
		//不同的document可以有不同的域,同一个document可以有相同的域。
		document.add(new TextField("filename", "新添加的文档", Store.YES));
		document.add(new TextField("content", "新添加的文档的内容", Store.NO));
		document.add(new TextField("content", "新添加的文档的内容第二个content", Store.YES));
		document.add(new TextField("content1", "新添加的文档的内容要能看到", Store.YES));
		//添加文档到索引库
		indexWriter.addDocument(document);
		//关闭indexwriter
		indexWriter.close();
		
	}

二、索引库的删除

2.1 删除全部
@Test
	public void testIndexDeleteAll() throws Exception{
		Analyzer analyzer = createAnalyzer();
		Directory directory = createDirectory();
		IndexWriter indexWriter = createIndexWriter(analyzer,directory);
		
		indexWriter.deleteAll();
		indexWriter.commit();
		indexWriter.close();
	}说明:将索引目录的索引信息全部删除,直接彻底删除,无法恢复。




2.2 根据条件删除

@Test
	public void testIndexDeleteByTerm() throws Exception{
		Analyzer analyzer = createAnalyzer();
		Directory directory = createDirectory();
		IndexWriter indexWriter = createIndexWriter(analyzer,directory);
		//根据名称进行删除
		//Term词元:第一次参数:域名,第二个参数:要删除含有此关键字的数据
		indexWriter.deleteDocuments(new Term("fileName","lucene"));
		indexWriter.commit();
		indexWriter.close();
	}

三、索引库的修改

/**
	 * 更新就是按照传入的Term进行搜索,如果找到结果就删除,将更新的内容重新生成一个Document对象
	 * 如果没有搜索到结果,那么就将更新的内容直接添加一个新的Document对象
	 * 
	 */
	@Test
	public void testIndexUpdate() throws Exception{
		Analyzer analyzer = createAnalyzer();
		Directory directory = createDirectory();
		IndexWriter indexWriter = createIndexWriter(analyzer,directory);
		
		//根据文件名称进行更新
		Term term = new Term("fileName","lucene");
		
		//更新的对象
		Document doc = new Document();
		doc.add(new TextField("fileName", "Jack test name",Store.YES));
		doc.add(new TextField("fileContext", "this is context",Store.NO));
		doc.add(new LongField("fileSize", 112L,Store.NO));
		indexWriter.updateDocument(term, doc);
		indexWriter.commit();
		indexWriter.close();
	}
源代码github地址:https://github.com/lucene-in-action/lucene-index-delete