1. 程式人生 > >Lucene(三)----索引流程程式碼開發

Lucene(三)----索引流程程式碼開發






package com.ken.lucene;

import java.io.File;

import org.apache.commons.io.FileUtils;
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;

public class FirstLucene {

	@Test
	public void test() throws Exception {
		// 1.建立一個indexwriter
		// 1)指定索引庫的存放位置Directory物件
		// 2)指定一個分析器,對文件內容進行分析
		Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
		Analyzer analyzer = new StandardAnalyzer();// 官方推薦
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
		IndexWriter indexWriter = new IndexWriter(directory, config);

		// 3.建立field物件,將field新增到document
		File f = new File("D:\\temp\\searchsource");
		File[] listFiles = f.listFiles();
		for (File file : listFiles) {
			// 2.建立document物件
			Document document = new Document();
			// 檔名稱
			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.NO);

			document.add(fileNameField);
			document.add(fileSizeField);
			document.add(filePathField);
			document.add(fileContentField);

			// 4.使用indexwriter物件將document物件寫入索引庫,此過程進行索引建立。並將索引和document物件寫入索引庫。
			indexWriter.addDocument(document);
		}

		// 5.關閉indexwriter物件
		indexWriter.close();
	}
}


執行:


命令執行:cmd執行:java  -jar lukeall-4.10.3.jar



原始碼下載