创建索引代码:
public void createIndex(String indexPath, String dataDir) throws IOException
{
//获取数据源文件列表
File[] files = new File(dataDir).listFiles();
//创建索引目錄
Directory directory = FSDirectory.open(new File(indexPath));
//創建分詞器
//
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
Analyzer analyzer = new PaodingAnalyzer();
//创建索引写入类
IndexWriter indexWriter = new IndexWriter(directory, analyzer, true, MaxFieldLength.LIMITED);
for (File file : files)
{
String content = FileOperation.readContents(file, "UTF-8");
String[] records = content.split("\r\n");
for (String record : records)
{
//创建Document对象
Document document = new Document();
//创建域
Field contentField = new Field("content", record, Store.YES, Index.ANALYZED);
Field nameField = new Field("filename", file.getName(), Store.YES, Index.ANALYZED);
document.add(nameField);
document.add(contentField);
indexWriter.addDocument(document);
}
}
indexWriter.optimize();
//查看有多少个索引
System.out.println("numDocs:" + indexWriter.numDocs());
indexWriter.close();
}