Lucene使用(一)

	/**
	 * 增加索引
	 * @throws IOException
	 */
	@Test
	public void  addIndex() throws IOException {
		//1.初始化索引
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
		Directory dir = FSDirectory.open(new File("/root/testindex"));
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
		IndexWriter writer = new IndexWriter(dir,iwc);
		
		//2.添加数据
		String[] ids = new String[]{"1","2","3","4","5",};
		String[] names = new String[]{"需要开启","需响应正文返回需要","调用适合","正文转换","增加了新注解 "};
		for(int i = 0 ; i< ids.length; i++){
			Document d = new Document();
			Field name = new Field("name", names[i], Store.YES, Index.ANALYZED);
			Field id = new Field("id", ids[i], Store.YES, Index.ANALYZED);
			d.add(name);
			d.add(id);
			writer.addDocument(d);
		}
		//3.保存数据
		writer.close();
	}



	/**
	 * 查询索引
	 * @throws IOException 
	 * @throws ParseException 
	 */
	@Test
	public void queryIndex() throws IOException, ParseException{
		String key = "需"; //搜索关键字
		
		//1.打开索引
		Directory dir = FSDirectory.open(new File("/root/testindex"));
		IndexReader reader = IndexReader.open(dir); //打开索引
		
		//2.初始化查询组建
		IndexSearcher searcher = new IndexSearcher(reader); //查询器
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); //分词器
		QueryParser parser = new QueryParser(Version.LUCENE_36,"name", analyzer); //对name查询解析器
		
		//3.查询
		Query query = parser.parse(QueryParser.escape(key)); //根据关键字返回封装的查询对象
		TopDocs docs = searcher.search(query, 10); //查询
		ScoreDoc[] scoreDocs = docs.scoreDocs;
		for(ScoreDoc s : scoreDocs){
		     Document doc = searcher.doc(s.doc);//获得docuemnt的id
		     String id = doc.getFieldable("id").stringValue();
		     String name = doc.getFieldable("name").stringValue();
		     System.out.println("id :" + id +"  name :" + name);
		}
		reader.close();
		searcher.close();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值