Lucene4.x 第一篇

项目地址:http://lucene.apache.org/core/

项目最新版本:4.2.1

相关Jar包下载:http://mirrors.cnnic.cn/apache/lucene/java/4.2.1/

 

我们还是从最简单的helloworld开始吧,lucene从广义上我们可以把他分为建立索引和查询索引。分别用以下代码来操作下吧。

   建立索引

Directory dir;
		IndexWriter indexWriter;
		try {
			dir = FSDirectory.open(new File("D:/index"));
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_42,analyzer);
			indexWriter = new IndexWriter(dir, iwc);
			
			for(int i = 0 ; i < 100 ; i++){
				Document doc = new Document();
				doc.add(new StringField("Id", "123456"+i, Store.YES));
				doc.add(new TextField("Content", "大家好,我叫xxx"+i, Store.YES));
				indexWriter.addDocument(doc);
			}
			indexWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 

 查询索引

Directory dir;
		try {
			dir = FSDirectory.open(new File("D:/index"));
			IndexReader reader=DirectoryReader.open(dir);  
	        IndexSearcher searcher=new IndexSearcher(reader);  
	        Term term=new Term("Id", "1234561");  
	        TermQuery query=new TermQuery(term);  
	        TopDocs topdocs=searcher.search(query, 5);  
	        ScoreDoc[] scoreDocs=topdocs.scoreDocs;  
	        System.out.println("search Totle:" + topdocs.totalHits+"\tmax score:"+topdocs.getMaxScore());  
	        for(int i=0; i < scoreDocs.length; i++) {  
	            int doc = scoreDocs[i].doc;  
	            Document document = searcher.doc(doc);  
	            System.out.println("Id:"+document.get("Id")+"\tcontent:"+document.get("Content"));  
	        }  
	        reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 

 

 

你可能感兴趣的:(lucene4.0)