Lucene實戰開發手記(三)--- 創建索引細節方法

本文介绍了一种用于构建文档及其附件索引的方法。主要内容包括:如何为文档主体创建索引,涉及ID、标题、内容等字段的处理;如何为文档附件创建索引,包括通过简单工厂模式选择合适的处理方式。该方法特别关注了HTML内容的提取及不同附件格式的支持。
	
	/**
	 * 文檔主體建立索引
	 * 注意文檔與附件分成不同的Document,但搜索到附件內容時,需鏈接到其所在文檔
	 * @param article
	 * @return
	 * @throws InterruptedException 
	 * @throws Exception 
	 */
	private Document createArticleIndex(Article article) throws Exception{		
		Document document = new Document();
		//ID
		document.add(new Field("id", article.getId(), Field.Store.YES,
				Field.Index.UN_TOKENIZED));
		//文檔ID
		document.add(new Field("articleId", article.getId(), Field.Store.YES,
				Field.Index.UN_TOKENIZED));
		//文檔標題
		document.add(new Field("topic", article.getTopic(), Field.Store.YES,
				Field.Index.TOKENIZED));
		//文檔分類
		document.add(new Field("categoryId", article.getCategoryId(),
				Field.Store.YES, Field.Index.TOKENIZED));
		
		String content = article.getContent();
		
		//注意文章內容支持html標簽,故此處需提取文本內容
		HTMLParser parser = new HTMLParser(new StringReader(content));	
		LineNumberReader reader = new LineNumberReader(parser.getReader());
		StringBuffer buffer = new StringBuffer("");		
	    for (String line = reader.readLine(); line != null; line = reader.readLine()){
	    	  buffer.append(line);		        
	    }	     
	    String contents = buffer.toString();
		
		document.add(new Field(DocHander.FIELD_CONTENT, contents,
				Field.Store.YES, Field.Index.TOKENIZED));
		return document;
	}
	
	/**
	 * 文檔附件建立索引
	 * @param article
	 * @param articleAttach
	 * @return
	 * @throws Exception
	 */
	private Document createAttachIndex(Article article, ArticleAttach articleAttach) throws Exception{
		Document attachDocument = null;    //注意上傳的附件,已經通過在之前被處理為byte[]形式
		if (articleAttach != null && articleAttach.getFileBlob().length > 0) {
			byte[] attach = articleAttach.getFileBlob();			
			String fileName = articleAttach.getFileName();
			
			//採用簡單工廠模式,不同的附件格式,採用不同的DocHander,具體實現詳見下篇
			DocHander docHander = DocHanderFactory.buildDocHander(fileName);
			
			attachDocument = docHander.getDocument(attach);
			
			attachDocument.add(new Field("fileName", articleAttach
					.getFileName(), Field.Store.YES, Field.Index.TOKENIZED));
			attachDocument.add(new Field("id", articleAttach.getId(),
					Field.Store.YES, Field.Index.UN_TOKENIZED));
			attachDocument.add(new Field("articleId", article.getId(),
					Field.Store.YES, Field.Index.UN_TOKENIZED));
			attachDocument.add(new Field("topic", article.getTopic(),
					Field.Store.YES, Field.Index.NO));
			attachDocument.add(new Field("categoryId", article.getCategoryId(),
					Field.Store.YES, Field.Index.TOKENIZED));
		}
		return attachDocument;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值