private Directory directory = new RAMDirectory();
private DirectoryReader ireader = null;
private IndexWriter iwriter = null;
private IKAnalyzer analyzer;
//存放索引文件的位置,即索引库
private String searchDir = "d:\\Test\\Index";
private static File indexFile = null;
/**
* 新增索引
*/
public void addIndex()throws Exception{
indexFile = new File(searchDir);
directory = FSDirectory.open(indexFile);
IndexWriterConfig iwConfig = new IndexWriterConfig(version, getAnalyzer());
iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwriter = new IndexWriter(directory,iwConfig);
Document doc = new Document();
doc.add(new TextField("id", "1",Field.Store.YES));
doc.add(new TextField("name", "王五",Field.Store.YES));
iwriter.addDocument(doc);
iwriter.close();
}
/**
* 更新索引
*/
public void updateIndex(String id) throws Exception{
indexFile = new File(searchDir);
directory = FSDirectory.open(indexFile);
IndexWriterConfig iwConfig = new IndexWriterConfig(version, getAnalyzer());
iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwriter = new IndexWriter(directory,iwConfig);
ireader = DirectoryReader.open(FSDirectory.open(indexFile));
Document doc = new Document();
doc.add(new TextField("id", "183",Field.Store.YES));
doc.add(new TextField("name", "王凯1",Field.Store.YES));
//第一个参数是删除含有term的document,第二个参数是更新后的docume
iwriter.updateDocument(new Term("id","183"), doc);
iwriter.close();
}
/**
* 删除索引
*/
public void deleteIndex(String id) throws Exception{
indexFile = new File(searchDir);
directory = FSDirectory.open(indexFile);
IndexWriterConfig iwConfig = new IndexWriterConfig(version, getAnalyzer());
iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwriter = new IndexWriter(directory,iwConfig);
ireader = DirectoryReader.open(FSDirectory.open(indexFile));
Term term = new Term("id",id); //---精确查找,删除此纪录
iwriter.deleteDocuments(term);
iwriter.close();
}