全文检索Lucence(四)——索引外篇(增、删、改代码封装篇)

    在Lucence中,对索引的操作就像普通数据库的Dao层的CRUD,于是把这块的代码提取出来,以便复用。这里没有太多的文字描述,基本就是代码的堆积。

    注意一点:Term是搜索的最小单位,代表某个 Field 中的一个关键词,如:<title, lucene>

1、创建索引:

	/**
	 * 添加/创建索引
	 * 
	 * @param doc
	 */
	public void save(Document doc) {
		IndexWriter indexWriter = null;
		try {<span style="white-space:pre">	</span>//MaxFieldLength.LIMITED表示只对前10000个字做索引 
<span style="white-space:pre">			</span>//参数true表示是否删除原来的索引后再重新创建,没有参数true,添加索引 
			indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
			indexWriter.addDocument(doc);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				indexWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


2、删除索引:

	/**
	 * Term是搜索的最小单位,代表某个 Field 中的一个关键词,如:<title, lucene>
	 * 
	 * new Term( "title", "lucene" );
	 * 
	 * new Term( "id", "5" );
	 * 
	 * new Term( "id", UUID );
	 * 
	 * @param term
	 */
	public void delete(Term term) {
		IndexWriter indexWriter = null;
		try {
			indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
			indexWriter.deleteDocuments(term);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				indexWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


3、更新索引:

	/**
	 * 更新索引
	 * 
	 * <pre>
	 * indexWriter.deleteDocuments(term);
	 * indexWriter.addDocument(doc);
	 * </pre>
	 * 
	 * @param term
	 * @param doc
	 */
	public void update(Term term, Document doc) {
		IndexWriter indexWriter = null;
		try {
			indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
			indexWriter.updateDocument(term, doc);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				indexWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


4、使用类对上面方法封装:

public class IndexDao {

	String indexPath = "。。。。。";

	// Analyzer analyzer = new StandardAnalyzer();

	Analyzer analyzer = new MMAnalyzer();// 词库分词

}
    

总结:

    这里只针对索引的增删改做封装,关于查询内容比较多,单独在后面的博客中介绍。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值