Lucene 学习笔记(3) :Hello Lucene(Lucene Index的创建和查找)

1、创建索引

public void Index()
	{
		IndexWriter iw = null;
		try
		{
			/**
			 * 1、创建文件目录
			 */
			// Directory directory=new RAMDirectory();//建立在内存中
			Directory directory = FSDirectory.open(new File(
					"c:/lucene/indexhello"));// 搜索存储在硬盘上
			/**
			 * 2、创建索引配置
			 */
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35,
					new StandardAnalyzer(Version.LUCENE_35));

			/**
			 * 3、创建IndexWriter
			 */
			iw = new IndexWriter(directory, iwc);
			/**
			 * 4、创建Document
			 */
			Document doc = null;
			/**
			 * 5、为Document添加filed
			 */
			File files = new File("c:/lucene/search");
			for (File file : files.listFiles())
			{
				doc = new Document();// 此处必须创建出一个对象
				doc.add(new Field("content", new FileReader(file)));
				doc.add(new Field("filename", file.getName(), Field.Store.YES,
						Field.Index.NOT_ANALYZED));
				doc.add(new Field("path", file.getAbsolutePath(),
						Field.Store.YES, Field.Index.NOT_ANALYZED));
				/**
				 * 6、通过IndexWriter将文档添加到索引中
				 */
				iw.addDocument(doc);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (iw != null)
				try
				{
					iw.close();// IndexWriter流必须关闭
				} catch (CorruptIndexException e)
				{
					e.printStackTrace();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
		}
	}


2、遍历索引

public void Serach()
	{
		IndexReader ir = null;
		try
		{
			/**
			 * 1、创建文件目录
			 */
			Directory directory = FSDirectory.open(new File(
					"c:/lucene/indexhello"));// 搜索存储在硬盘上
			/**
			 * 2、创建IndexReader
			 */
			ir = IndexReader.open(directory);
			/**
			 * 3、根据IndexReader创建IndexSearcher
			 */
			IndexSearcher search = new IndexSearcher(ir);
			/**
			 * 4、创建Query new QueryParser(1,2,3) 第二个参数传入的字段名
			 */
			QueryParser parser = new QueryParser(Version.LUCENE_35, "content",
					new StandardAnalyzer(Version.LUCENE_35));
			/**
			 * QueryParser.parse(String queryContent)
			 */
			Query query = parser.parse("java");
			/**
			 * 根据IndexSearcher得到TopDocs
			 */
			TopDocs Tdoc = search.search(query, 10);
			/**
			 * 根据TopDocs得到ScoreDoc
			 */
			ScoreDoc[] Sdocs = Tdoc.scoreDocs;
			for (ScoreDoc sdoc : Sdocs)
			{
				/**
				 * ScoreDoc.doc得到文档ID
				 * IndexSearcher.doc(int DocID)获取到相应ID的Document
				 */
				Document doc = search.doc(sdoc.doc);
				/**
				 *  根据Document获取其详细的信息 
				 */
				System.out.println(doc.get("filename") + "[" + doc.get("path")
						+ "]");
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			ir.clone();
		}
	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值