初试 Lucene3.3.0

从网上下载了个3.3.0版本的.看着demo做了个例子:

public class IndexClasss {

	String path = "c:\\lucene\\";
	String path2 = "e:\\api\\"; 
		
	
	public void  createIndex() throws IOException{
		Directory dir = FSDirectory.open(new File(path));
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
		IndexWriterConfig con = new IndexWriterConfig(Version.LUCENE_33,analyzer);
		IndexWriter writer = new IndexWriter(dir,con);
		Document doc = new Document();
		Date start = new Date();
		if(addField2Document(listFiles(path2),doc)){
			Date end = new Date();
			System.out.println("total time: " + (end.getTime()-start.getTime()) + " ms");
			System.out.println("---------------------------------------");
		}else{
			System.out.println("false to create Index by path :" +path);
		}
		writer.addDocument(doc);
		writer.optimize();
		writer.close();
	}
	
	public boolean addField2Document(List<Fieldable> list,Document doc){
		if(list == null || list.isEmpty()){
			return false;
		}else{
			for(int a=0;a<list.size();a++){
				doc.add(list.get(a));
			}
		}
		return true;
	}
	
	public List listFiles(String path){
		if(path==null || "".equals(path)){
			return null;
		}
		List<Fieldable> fields = new ArrayList();
		File files = new File(path);
		if(files.isDirectory()){
			String[] fs = files.list();
			for(int a=0;a<fs.length;a++){
				System.out.println("found " + fs[a]);
				fields.add(getFieldable(new File(path,fs[a])));
			}
		}else{
			fields.add(getFieldable(new File(path)));
		}
		System.out.println("found files : \t"+fields.size());
		System.out.println("create index files finished....");
		return fields;
	}
	
	
	public Fieldable getFieldable(File file){
		Field field = new Field("path",file.getPath(),Field.Store.YES,Field.Index.ANALYZED);
		return field;
	}
	
	public void QuerySearcher(String querystr) throws ParseException, IOException{
		Directory dir = FSDirectory.open(new File(path));
		IndexSearcher search = new IndexSearcher(dir);
		System.out.println("found index : " +dir.listAll().length +" files");
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
		QueryParser parse = new QueryParser(Version.LUCENE_33,"path",analyzer);
		Query query = parse.parse(querystr);
		TopDocs it = search.search(query,100);
		System.out.println("search : " + query.toString());
		ScoreDoc[] docs = it.scoreDocs;
		for(int a=0;a<docs.length;a++){
			System.out.println(a+"\t"+docs.toString());
		}
	}
	
	public Fieldable getField(String name,String value){
		return new Field(name,value,Field.Store.YES,Field.Index.ANALYZED);
	}
	
	public static void main(String[] arg) throws IOException, ParseException{
		IndexClasss index  =new IndexClasss();
		index.createIndex();
		index.QuerySearcher("Struts1.3.chm");
	}
}

你可能感兴趣的:(初试 Lucene3.3.0)