索引庫(kù)的添加
- 向索引庫(kù)中添加document對(duì)象透敌, 步驟
- 第一步:先創(chuàng)建一個(gè)indexwriter對(duì)象
- 第二步:創(chuàng)建一個(gè)document對(duì)象
- 第三步:把document對(duì)象寫入索引庫(kù)
- 第四步:關(guān)閉indexwriter么库。
/**
* 刪除索引
* @throws Exception
*/
@Test
public void testDeleteIndex() throws Exception{
//創(chuàng)建分詞器,StandardAnalyzer標(biāo)準(zhǔn)分詞器,標(biāo)準(zhǔn)分詞器對(duì)英文分詞效果很好,對(duì)中文是單字分詞
Analyzer analyzer = new IKAnalyzer();
//指定索引和文檔存儲(chǔ)的目錄
FSDirectory directory = FSDirectory.open(new File("D:\\BaiduNetdiskDownload\\lucene_day01\\tmp"));
//創(chuàng)建寫對(duì)象的初始化對(duì)象
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
//創(chuàng)建索引和文檔寫對(duì)象
IndexWriter indexWriter = new IndexWriter(directory , config);
//刪除所有
// indexWriter.deleteAll();
/**
* Term詞元,就是一個(gè)詞,
* 第一個(gè)參數(shù):域名,
* 第二個(gè)參數(shù):要?jiǎng)h除含有此關(guān)鍵詞的數(shù)據(jù)
*/
Term term = new Term("fileName" , "apache");
//根據(jù)名稱進(jìn)行刪除
indexWriter.deleteDocuments(term);
//提交
indexWriter.commit();
//關(guān)閉
indexWriter.close();
}
/**
* 更新就是按照傳入的Term進(jìn)行搜索,如果找到結(jié)果那么刪除,將更新的內(nèi)容重新生成一個(gè)Document對(duì)象
* 如果沒有搜索到結(jié)果,那么將更新的內(nèi)容直接添加一個(gè)新的Document對(duì)象
* @throws Exception
*/
索引庫(kù)刪除
刪除全部
//刪除全部索引
@Test
public void deleteAllIndex() throws Exception {
IndexWriter indexWriter = getIndexWriter();
//刪除全部索引
indexWriter.deleteAll();
//關(guān)閉indexwriter
indexWriter.close();
}
說明:將索引目錄的索引信息全部刪除上炎,直接徹底刪除拴竹,無法恢復(fù)扫俺。
此方法慎用B酚ァ惨篱!
指定查詢條件刪除
//根據(jù)查詢條件刪除索引
@Test
public void deleteIndexByQuery() throws Exception {
IndexWriter indexWriter = getIndexWriter();
//創(chuàng)建一個(gè)查詢條件
Query query = new TermQuery(new Term("filename", "apache"));
//根據(jù)查詢條件刪除
indexWriter.deleteDocuments(query);
//關(guān)閉indexwriter
indexWriter.close();
}
索引庫(kù)的修改
原理就是先刪除后添加盏筐。
@Test
public void testUpdateIndex() throws Exception{
//創(chuàng)建分詞器,StandardAnalyzer標(biāo)準(zhǔn)分詞器,標(biāo)準(zhǔn)分詞器對(duì)英文分詞效果很好,對(duì)中文是單字分詞
Analyzer analyzer = new IKAnalyzer();
//指定索引和文檔存儲(chǔ)的目錄
FSDirectory directory = FSDirectory.open(new File("D:\\BaiduNetdiskDownload\\lucene_day01\\tmp"));
//創(chuàng)建寫對(duì)象的初始化對(duì)象
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
//創(chuàng)建索引和文檔寫對(duì)象
IndexWriter indexWriter = new IndexWriter(directory , config);
Term term = new Term("fileName","1.create web page.txt");
Document doc = new Document();
doc.add(new TextField("fileName", "xxxxxxx", Field.Store.YES));
doc.add(new TextField("fileContext", "xxx I like you very much!", Field.Store.YES));
doc.add(new LongField("fileSize", 100L, Field.Store.YES));
indexWriter.updateDocument(term , doc);
//提交
indexWriter.commit();
//關(guān)閉
indexWriter.close();
}