Lucene Demo

Lucene Demo

/**
 * 
 * 
 * 
 * @author Administrator
 *
 */
public class TestLucene {
	/**
	 * 通过indexWriter 对数据建立索引....
	 * @throws IOException 
	 * 
	 */
	@Test
	public void testCreateIndex() throws IOException{
		//索引存放的位置...
		Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));
		//lucene 的当前使用版本...
		Version version=Version.LUCENE_44;
		/**
		 * 分词器
		 * 
		 * 对一段文本进行分词....  
		 * 因为Analyzer  是一个抽象类...
		 * 因为每个国家使用的语言都不一样。
		 * 
		 * 对中文进行分词,new 中文对应的分词器的实现...
		 * 
		 */
		Analyzer analyzer=new  StandardAnalyzer(version);
		
		//索引写入配置...
		IndexWriterConfig indexWriterConfig=new IndexWriterConfig(version, analyzer);
		
		//创建操作索引的类...
		IndexWriter indexWriter=new IndexWriter(directory, indexWriterConfig);
		/**
		 * 向索引库当中添加数据...
		 * 索引库当中存储的都是document 对象....
		 * 
		 */
		int id=2;
		String title="lucene 是 apaches 一个全文检索工具包";
		String content="新疆暴恐后游客减4成 奖赴疆游500元人 ";
		String author="爱新觉罗霍思燕";
		Document document=new Document();
		//不同的数据类型,就构造不同的实现...
		/**
		 * 1:字段对应的名称
		 * 2:字段对应的值
		 * 3:Store 是否存储...
		 */
		IndexableField idfield=new IntField("id", id, Store.YES);
		
		IndexableField titlefield=new TextField("title", title, Store.YES);
		
		IndexableField contentfield=new TextField("content", content, Store.YES);
		IndexableField authorfield=new StringField("author", author, Store.YES);
		document.add(idfield);
		document.add(titlefield);
		document.add(contentfield);
		document.add(authorfield);
		//写入索引...
		indexWriter.addDocument(document);
		
		indexWriter.close();
	}
	@Test
	public void testSearcher() throws IOException{
		//索引存放的位置...
		Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));
		
		//读取硬盘上面的索引...
		IndexReader indexReader=DirectoryReader.open(directory);
		
		
		//创建用于搜索索引的对象...
		IndexSearcher indexSearcher=new IndexSearcher(indexReader);
		
		
//		/query 是一个查询条件对象....它是一个抽象类,不同的查询规则有子类来实现
		/**
		 * 1:字段的名称
		 * 
		 * 2:字段对应的值...
		 * 
		 */
		Query query=new TermQuery(new Term("title", "政治局研究进一步推进新疆社会稳定等工作"));
		
		//查找符合query 条件的前面N 条记录...
		TopDocs topDocs=indexSearcher.search(query, 10);
		//这个数组里面存放了document 的id,还需要根据id 在找到对应的document....
		ScoreDoc scoreDocs []=topDocs.scoreDocs;
		
		System.out.println("==="+scoreDocs.length);
		for(ScoreDoc scoreDoc:scoreDocs){
			int docID=scoreDoc.doc;
			Document document=indexSearcher.doc(docID);
			String title=document.get("title");
			String content=document.get("content");
			String id=document.get("id");
			System.out.println(title);
			System.out.println(content);
			System.out.println(id);
			
			
		}
		
		
		
	}
	
	
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值