Lucene6.0學習筆記——創建索引

1.定義相關變量java

private final static String filePath="E:\\workspace\\luceneDemo\\files";
private final static Path indexPath=Paths.get("E:\\workspace\\luceneDemo\\indexStore");
public static Analyzer analyzer = new SmartChineseAnalyzer();

filePath:須要建立索引的源文件地址spa

indexPath:索引保存地址code

analyzer:定義分詞器,這裏採用lucene自帶的中文分詞器排序

2.創建索引索引

public static void createIndex(){
	List<Document> doc = File2DocumentUtil.files2Document(filePath);
	try {
		/*索引文件採用物理存儲*/
		FSDirectory directory = FSDirectory.open(indexPath);
		/*索引文件內存存儲*/
		//RAMDirectory directory1 = new RAMDirectory();
		//配置indexWriter,寫入索引
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		IndexWriter indexWriter=new IndexWriter(directory, config);
		//建立以前刪除全部索引
		indexWriter.deleteAll();
		//添加須要創建索引的Document
		indexWriter.addDocuments(doc);
		//提交寫入
		indexWriter.commit();
		//關閉indexWriter
		indexWriter.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

3.文件轉Document方法內存

public static List<Document> files2Document(String filePath) {
	File dir=new File(filePath);
	List<Document> list=new ArrayList<>();
	for(File file:dir.listFiles()){
		Document doc=new Document();
		doc.add(new TextField("name", file.getName(), Store.YES));
		doc.add(new StringField("path", file.getPath(), Store.YES));
		/*設置排序字段*/
		doc.add(new NumericDocValuesField("size",file.length()));  
		doc.add(new StringField("size", String.valueOf(file.length()), Store.YES));
		doc.add(new TextField("content", getFileContent(file), Store.YES));
		list.add(doc);
	}
	return list;
}

StringField:不會進行分詞操做;get

TextField:會進行分詞操做。it

相關文章
相關標籤/搜索