對索引操作的類為KbIndexProcesser 

文檔主體類:Article

public class Article {
	private String id;
	private String topic;
	private String content;
	private String categoryId;
	private String category;
   .......
}

 附件實體類:ArticleAttach

public class ArticleAttach {
	private String id;
	private String articleId;
	private String fileName;
	private byte[] fileBlob;
......
}

 

KbIndexProcesser 創建索引的代碼:

public class KbIndexProcesser {

	private static final String INDEX_STORE_PATH = "luceneIndex";//索引存放路徑
	private static final int CONTENTS_SHOW_LENGTH = 200;//文字摘要的長度
	private static final int MAX_RESULT = 20;//最大的搜索結果數,沒做分頁
		
	/**
	 * 創建索引
	 * @param article
	 * @param articleAttach
	 * @param attachOnly 隻為附附建索引嗎
	 * @throws LuceneException
	 */
	public  void createIndex(Article article, ArticleAttach articleAttach, boolean attachOnly)
			throws LuceneException {
		IndexWriter indexWriter = null;
		File indexDir = new File(INDEX_STORE_PATH);
		//debug
		
		Analyzer analyzer = new CJKAnalyzer();

		long startTime = new Date().getTime();
		
		try{
			if (indexDir.exists()) {
				indexWriter = new IndexWriter(indexDir, analyzer, false);
			} else {
				indexWriter = new IndexWriter(indexDir, analyzer, true);
			}
			
			if (attachOnly == false){
				//文章主體建索引
				Document document = this.createArticleIndex(article);
				indexWriter.addDocument(document);
			}			
			
			// 附件建索引
			if (articleAttach != null){
				Document attachDocument = this.createAttachIndex(article, articleAttach);
				indexWriter.addDocument(attachDocument);
			}

			indexWriter.optimize();
			indexWriter.close();
		} catch(Exception ex){
			ex.printStackTrace();
			throw new LuceneException();
		}
		
		long endTime = new Date().getTime();
		System.out.println("It takes " + (endTime - startTime)
				+ " milliseconds to create index for the files in directory "
				+ indexDir.getPath());
	}
}

 所用分詞器為CJKAnalyzer,曾使用CWordAnalyzer 分詞,但它在高亮顯示處理時會報錯,不知是何故,故棄之。

评论
发表评论

您还没有登录,请登录后发表评论