lucene入門インスタンス1(書き込みインデックス)
copy lucene in actionの入門インスタンスコード:
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelectorResult;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Index {
public static void main(String[] args) throws Exception {
String indexDir = "F:\\workspace\\JavaDemo\\src\\com\\s\\lucene\\index";// lucene
String dataDir = "F:\\workspace\\JavaDemo\\src\\com\\s\\lucene";//lucene
long start = System.currentTimeMillis();
Index indexer = new Index(indexDir);// indexWriter
int numIndexed;
try{
numIndexed = indexer.index(dataDir, new TextFilesFilter());//
}finally{
indexer.close();
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
private IndexWriter writer;
public Index(String indexDir) throws IOException{
Directory dir = FSDirectory.open(new File(indexDir));//
// writer IndexWriterConfig
writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws IOException{
writer.close();
}
public int index(String dataDir,FileFilter filter) throws Exception{
File[] files = new File(dataDir).listFiles();//
for (File f : files) {
if(!f.isDirectory() && filter.accept(f)){
indexFile(f);// ,
}
}
return writer.numDocs();
}
public static class TextFilesFilter implements FileFilter{
public boolean accept(File path){
return path.getName().toLowerCase().endsWith(".txt");
}
}
protected Document getDocument(File f) throws Exception{
Document doc = new Document();
doc.add(new Field("contents",new FileReader(f)));//
doc.add(new Field("filename",f.getName(),
Field.Store.YES,Field.Index.NOT_ANALYZED));//
doc.add(new Field("fullpath",f.getCanonicalPath(),
Field.Store.YES,Field.Index.NOT_ANALYZED)); //
return doc;
}
private void indexFile(File f) throws Exception{
Document doc = getDocument(f);// document
writer.addDocument(doc);// document
}
}