lucene5(2)索引增删改查 祈雨的笔记 2017-10-01 lucene5 1、增加索引12345678910@Testpublic void TestInsert() throws Exception { IndexWriter writer = getIndexWriter(indexDir); Document document = new Document(); // 添加一个文档信息,相当于一个数据库表字段 document.add(new TextField("name", "hello world", Field.Store.YES)); document.add(new TextField("describes", "测试luence", Field.Store.YES)); writer.addDocument(document); writer.close();} 2、更新索引123456789101112@Testpublic void TestUpdate() throws Exception { // Lucene并没有提供更新,这里的更新操作相当于新增,他并不会去掉原来的信息 IndexWriter writer = getIndexWriter(indexDir); Document doc = new Document(); doc.add(new StringField("name", "ckl", Field.Store.YES)); doc.add(new StringField("describes", "chenkailing", Field.Store.YES)); writer.updateDocument(new Term("name", "hello world"), doc); //需要将原来的索引删除 // TODO writer.close();} 3、删除索引12345678910111213@Testpublic void TestDelete() throws Exception { IndexWriter writer = getIndexWriter(indexDir); QueryParser parser = new QueryParser("name", getAnalyzer()); Query query = parser.parse("ckl"); // 此时删除的文档并不会被完全删除,而是存储在一个回收站中的,可以恢复 writer.deleteDocuments(query); // 强制合并删除的索引信息,索引量大的时候不推荐使用,真正的删除 writer.forceMergeDeletes(); //更改索引要提交,和提交数据库事务一个概念,真正的删除 writer.commit(); writer.close();} 4、查询索引123456789101112131415@Testpublic void TestSearch() throws Exception { IndexReader reader = getIndexReader(); IndexSearcher searcher = new IndexSearcher(reader); // 指定Document的某个属性 QueryParser parser = new QueryParser("name", getAnalyzer()); // 指定索引内容,对应某个分词 Query query = parser.parse("ckl"); TopDocs hits = searcher.search(query, 10); for (ScoreDoc sd : hits.scoreDocs) { Document doc = searcher.doc(sd.doc); System.out.println("name:" + doc.get("name") + ",describes:" + doc.get("describes")); } reader.close();} 5、读取索引信息123456789public static IndexReader getIndexReader() throws Exception { IndexReader reader = null; reader = DirectoryReader.open(getDirectory(indexDir)); // 通过reader可以有效的获取到文档的数量 System.out.println("当前存储的文档数:" + reader.numDocs()); System.out.println("回收站的文档数:" + reader.numDeletedDocs()); System.out.println("当前存储的文档数,包含回收站的文档:" + reader.maxDoc()); return reader;}