Lucene実戦開発手記(二)---インデックスマスターメソッドの作成

2082 ワード

インデックス操作のクラスは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分詞を使用していたが、ハイライト表示処理時にエラーが発生し、なぜか捨てられた.