(2)Lucene的HelloWorld

                                            Lucene6.5.0

创建Lucene索引

涉及到的类:Directory  FSDirectory  

                        IndexWriterConfig  StandardAnalyzer  IndexWriter

                        Document  FieldType  Field

创建索引的代码

public void createIndex(){

    Directory directory = null;

    IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());

    IndexWriter iwriter = null;

    Document d = null;

    FieldType fieldType = new FieldType();

    fieldType.setStored(false);

                    fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);

FieldType fieldType1 = new FieldType();

fieldType1.setStored(true);

fieldType1.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);

try {

//创建索引目录

directory = FSDirectory.open(Paths.get(Constant.INDE_DIR));

//创建IndexWriter写索引

iwriter = new IndexWriter(directory, config);

//获取文件数据文件夹

File files = new File(Constant.FILE_DIR);

for(File f : files.listFiles()){

//创建一片文档

d = new Document();

//给文档添加域

d.add(new Field("content", new FileReader(f),fieldType) );

d.add(new Field("title", f.getName(), fieldType1));

d.add(new Field("path", f.getPath(), fieldType1));

iwriter.addDocument(d);

}

} catch (IOException e) {

e.printStackTrace();

}finally{

if(iwriter != null){

try {

iwriter.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

directory.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}


你可能感兴趣的:((2)Lucene的HelloWorld)