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