lucene入门实例

public class HelloLucene {

	/**
	 * 建立索引
	 */
	public void index() {
		IndexWriter writer = null;
		try {
			//1.创建Directory
			Directory directory = FSDirectory.open(new File("e:/lucene/index01"));
			//2.创建indexWriter
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_2, new StandardAnalyzer());
			writer = new IndexWriter(directory, config);
			//3.创建document对象
			Document doc = null;
			//4.位document添加field
			File files = new File("e:/lucene/example");
			for (File file: files.listFiles()) {
				doc = new Document();
				doc.add(new Field("content", new FileReader(file),TextField.TYPE_NOT_STORED));
				doc.add(new Field("path", file.getAbsolutePath(), TextField.TYPE_STORED));
				doc.add(new Field("fileName", file.getName(), TextField.TYPE_STORED));
				//通过indexWriter添加文档到索引中
				writer.addDocument(doc);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
				try {
					if (writer != null) {
						writer.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		

	}
	public void search() {
		try {
			//1.创建directory
			Directory directory = FSDirectory.open(new File("e:/lucene/index01"));
			//2.创建indexReader
			IndexReader reader = DirectoryReader.open(directory);
			//3.根据indexReader创建indexSerach
			IndexSearcher search = new IndexSearcher(reader);
			//4.创建搜索的query
			//创建query来确定搜索文件的内容贴,第一个参数为搜索的域
			QueryParser parse = new QueryParser("content", new StandardAnalyzer());
			//创建query表示搜索域content中包含Java的文档
			Query query = parse.parse("java");
			//5.根据search搜索并返回topDocs
			TopDocs tds = search.search(query, 10);
			//6.根据topDocs获取ScoreDoc对象
			ScoreDoc[] docs = tds.scoreDocs;
			for (ScoreDoc sd : docs) {
			//7.根据search和ScoreDoc对像获取具体的document,sd.doc位为档的id
				Document document = search.doc(sd.doc);
			//8.根据document对象获取相应的值
				System.out.println(document.get("fileName")+"["+document.get("path")+"]");
			//9.关闭Reader
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		
		new HelloLucene().index();
		new HelloLucene().search();
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值