Lucene3.6.1实例

//Lucene 3.6.1 实例:
public class LuceneTest{
        public static void main(String[] args) throws Exception {
			File file = new File("E:\\Workspaces\\LuceneAnalyzer\\Index");
            //从硬盘读取目录.
            Directory dir = FSDirectory.open(file);
			//传入版本号,分词器.
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,analyzer);
			iwc.setOpenMode(OpenMode.CREATE);			//即创建新索引文件.
//			iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);	//表示创建或追加到已有的索引文件.
			//传入目录和写入配置.
			IndexWriter indexWriter = new IndexWriter(dir, iwc);
		
			//创建文档对象.
			Document doc = new Document();
			//写入数据
			doc.add(new Field("gid", "1", Store.YES , Index.ANALYZED));
			doc.add(new Field("content", "中文分词", Store.YES , Index.ANALYZED));
			//添加到文档             
			indexWriter.addDocument(doc);
			//一定要关闭写入器, 不然是不会被写入到硬盘的.
			indexWriter.close();
		
	        //创建一个读入器.
			IndexReader indexReader = IndexReader.open(FSDirectory.open(file));
			//创建一个查询器.传入读入器.
			IndexSearcher indexSerach = new IndexSearcher(indexReader);
			//创建一个查询,传入版本号,要查询的范围,分词器.
			QueryParser queryParser = new QueryParser(Version.LUCENE_36, "content", analyzer);
			//要查询的内容.
			Query query = queryParser.parse("中文");
			//开始查询.传入查询,最大返回条数.
			TopDocs topDocs = indexSerach.search(query, 10);
		
			System.out.println("匹配条数:" + topDocs.totalHits);
			indexSerach.close();
			indexReader.clone();
		
                    //遍历.
			for (ScoreDoc topDoc : topDocs.scoreDocs) {
				int docid = topDoc.doc;
				System.out.println(docid);		//文档内部编号.
				Document tempdoc = indexSerach.doc(docid);
				System.out.println(tempdoc.get("content"));
		}
	}
}

你可能感兴趣的:(Java,Lucene)