您的位置:首页 > 其它

Lucene6.0学习笔记——建立索引

2016-07-15 00:00 796 查看
1.定义相关变量

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:需要创建索引的源文件地址

indexPath:索引保存地址

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:不会进行分词操作;

TextField:会进行分词操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: