`
longzhun
  • 浏览: 360901 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

即时更新索引思路

 
阅读更多

 

1.用户发表一篇文章,即时添加索引.

2.用户修改一篇文章,即时更新索引.

3.用户删除一篇文章,即时删除索引.

 

/**
	 * 添加文章,除向数据库添加文章外,为该文章创建索引
	 * 
	 * @return
	 * @throws Exception
	 */
	public String articleAdd() throws Exception {
		Integer articleId = this.articleManager.articleInsert(article);
		article.setId(articleId);
		this.createIndex(article);
		return SUCCESS;
	}

 

/**
	 * 为该文章创建索引的方法
	 * 
	 * @return
	 * @throws Exception
	 */
	public void createIndex(Article article) throws Exception {
		// 实例化分词器,使用的是中文分词器
		Analyzer analyzer = new PaodingAnalyzer();
		// 指定要保存的文件路径并保存到FSDirectory中
		System.out.println(URLDecoder.decode(
				AnalyzerAction.class.getResource("/date/index/article/")
						.toString(), "UTF-8").substring(6));
		FSDirectory directory = FSDirectory.getDirectory(URLDecoder.decode(
				AnalyzerAction.class.getResource("/date/index/article/")
						.toString(), "UTF-8").substring(6));
		// true表示覆盖原来已经创建的索引,如果是false表示不覆盖,而是继续添加索引
		IndexWriter writer = new IndexWriter(directory, analyzer, false);

		Document doc = new Document();
		doc.add(new Field("id", String.valueOf(article.getId()),
				Field.Store.YES, Field.Index.UN_TOKENIZED));
		doc.add(new Field("article_title", article.getArticleTitle(),
				Field.Store.YES, Field.Index.TOKENIZED));
		String content = FunctionUtil.Html2Text(article.getArticleContent());
		doc.add(new Field("article_content", content, Field.Store.YES,
				Field.Index.TOKENIZED));
		writer.addDocument(doc);
		writer.optimize();
		writer.close();
	}

 

	public void deleteIndex(Article article)throws Exception{
		// 实例化分词器,使用的是中文分词器
		Analyzer analyzer = new PaodingAnalyzer();
		// 指定要保存的文件路径并保存到FSDirectory中
		System.out.println(URLDecoder.decode(
				AnalyzerAction.class.getResource("/date/index/article/")
						.toString(), "UTF-8").substring(6));
		FSDirectory directory = FSDirectory.getDirectory(URLDecoder.decode(
				AnalyzerAction.class.getResource("/date/index/article/")
						.toString(), "UTF-8").substring(6));
		// true表示覆盖原来已经创建的索引,如果是false表示不覆盖,而是继续添加索引
		IndexWriter writer = new IndexWriter(directory, analyzer, false);
		writer.deleteDocuments(new Term("id",String.valueOf(article.getId())));
		writer.optimize();
		writer.close();
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics