1. 程式人生 > >一、建立索引之程式碼開發

一、建立索引之程式碼開發

jar包:

Lucene包:

lucene-core-4.10.3.jar

lucene-analyzers-common-4.10.3.jar

lucene-queryparser-4.10.3.jar

 

其它:

commons-io-2.4.jar

junit-4.9.jar

package com.itheima.lucene;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
/**
 * Lucene入門
 * 建立索引
 * 查詢索引
 * @author mjl
 *
 */
public class FirstLucene {

	/**
	 * @throws IOException 
	 * 
	 */
	@Test
	public void testIndex() throws IOException{
	//	第一步:建立一個java工程,並匯入jar包。
	//	第二步:建立一個indexwriter物件。open(new File("D:\\temp\\index"));
		//	1)指定索引庫的存放位置Directory物件
		//	2)指定一個分析器,對文件內容進行分析
		Directory directory = FSDirectory.open(new File("D:\\lucenesolr\\temp")); 
		Analyzer analyzer = new StandardAnalyzer();
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
		IndexWriter indexWriter = new IndexWriter(directory,config);
		
	//	第三步:建立document物件。
		Document document = new Document();
	//	第四步:建立field物件,將field新增到document物件中。
		File f = new File("D:\\lucenesolr\\searchsource");
		File[] listFiles = f.listFiles();
		for (File file : listFiles) {
			//檔名稱
			String file_name = file.getName();
			Field fileNameField = new TextField("fileName", file_name, Store.YES);
			//檔案大小
			long file_size = FileUtils.sizeOf(file);
			Field fileSizeField = new LongField("fileSize", file_size, Store.YES);
			//檔案路徑
			String file_path = file.getPath();
			Field filePathField = new StoredField("filePath", file_path);
			//檔案內容
			String file_content = FileUtils.readFileToString(file);
			Field fileContentField = new TextField("fileContent", file_content, Store.YES);
			
			document.add(fileNameField);
			document.add(fileSizeField);
			document.add(filePathField);
			document.add(fileContentField);
			
//			第五步:使用indexwriter物件將document物件寫入索引庫,此過程進行索引建立。並將索引和document物件寫入索引庫。
			indexWriter.addDocument(document);
		}
	
	//	第六步:關閉IndexWriter物件。
		indexWriter.close();
		
	}
}