Lucene学习笔记2-Lucene的CRUD(V7.1)

时间:2022-06-02 04:42:26
在进行CRUD的时候请注意IndexWriterConfig的设置。
public class IndexCRUD {
private String ids[]={"","",""};
private String citys[]={"jining","suzhou","shanghai"};
private String desc[]={
"Qingdao is a beautiful city.",
"Nanjing is a city of culture.",
"Shanghai is a bustling city."
}; private Directory dir; private IndexWriter getWriter()throws Exception{
dir= FSDirectory.open(Paths.get(LuceneConstants.IndexDir01));
Analyzer analyzer=new StandardAnalyzer();
IndexWriterConfig config=new IndexWriterConfig(analyzer);
//config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);//删除和修改的时候不能把OpenMode设为CREATE,否则会忽略term全部删除
IndexWriter indexWriter=new IndexWriter(dir,config);
return indexWriter;
}   //建立索引
public void createUpIndex() throws Exception{
IndexWriter indexWriter=getWriter(); for(int i=;i<ids.length;i++){
Document document=new Document();
document.add(new StringField("id",ids[i], Field.Store.YES));
document.add(new StringField("city",citys[i],Field.Store.YES));
document.add(new TextField("desc",desc[i],Field.Store.YES));
indexWriter.addDocument(document);
}
indexWriter.close();
}   //删除
public void deleteWithoutMerge()throws Exception {
IndexWriter writer = getWriter();
System.out.println("删除前:" + writer.numDocs());
writer.deleteDocuments(new Term("id", ""));// 强制删除此时删除的文档并不会被完全删除,而是存储在一个回收站中的,可以恢复
writer.commit(); //更改索引要提交,和提交数据库事务一个概念,真正的删除
System.out.println("writer.maxDoc():" + writer.maxDoc());
System.out.println("writer.numDocs():" + writer.numDocs());
writer.close();
} //删除后合并索引
public void DeleteWithMerge()throws Exception{
IndexWriter writer=getWriter();
System.out.println("删除前:"+writer.numDocs());
writer.deleteDocuments(new Term("id",""));// 强制删除此时删除的文档并不会被完全删除,而是存储在一个回收站中的,可以恢复
writer.forceMergeDeletes(); //强制合并删除的索引信息,索引量大的时候不推荐使用,真正的删除
writer.commit();
System.out.println("writer.maxDoc():"+writer.maxDoc());
System.out.println("writer.numDocs():"+writer.numDocs());
writer.close();
} public void update()throws Exception{
IndexWriter writer=getWriter();
Document doc=new Document();
doc.add(new StringField("id", "", Field.Store.YES));
doc.add(new StringField("city","qingdao",Field.Store.YES));
doc.add(new TextField("desc", "It's a dressed city.", Field.Store.YES));
writer.updateDocument(new Term("id",""), doc);
writer.close();
} public List<String> Search() throws Exception{
QueryParser queryParser=new QueryParser("desc",new StandardAnalyzer());
Query query=queryParser.parse("city"); if (null==dir) dir= FSDirectory.open(Paths.get(LuceneConstants.IndexDir01));
IndexReader reader=DirectoryReader.open(dir);
IndexSearcher searcher=new IndexSearcher(reader);
TopDocs topDocs=searcher.search(query,); List<String> list=new ArrayList<String>();
for (ScoreDoc scoreDoc:topDocs.scoreDocs) {
Document document = searcher.doc(scoreDoc.doc);
list.add(document.get("id")+document.get("city")+":"+document.get("desc"));
}
reader.close(); return list;
}
}