lucene初级入门

1、Lucene的核心jar包

lucene-core-4.3.1.jar

lucene-analyzers-common-4.3.1.jar

lucene-queryparser-4.3.1.jar

2、主要开发包说明

org.apache.lucene.analysis:语言分析器,主要用于分词

org.apache.lucene.document:索引文档的管理

org.apache.lucene.index:索引管理,如增、删、改

org.apache.lucene.queryparser:查询分析

org.apache.lucene.search:检索管理

org.apache.lucene.store:数据存储管理

org.apache.lucene.util:工具包

3、写入索引操作的核心类

Directory:代表索引文档的存储位置,这是一个抽象类有FSDirectoryRAMDirectory两个主要子类。前者将索引写入文件系统,后者将索引文档写入内存。

Analyzer:建立索引时使用的分析器,主要子类有StandardAnalyzer(一个汉字一个词),还可以由第三方提供如开源社区提供一些中文分词器。

IndexWriterConfig:操作索引库的配置信息

IndexWriter:建立索引的核心类,用来操作索引(增、删、改)

Document:代表一个索引文档

Field:代表索引文档中存储的数据,新版本的Lucene进行了细化给出了多个子类:IntFieldLongFieldFloatFieldDoubleFieldTextFieldStringField等。

4、写入索引

public class IndexFile {
	public static void main(String[] args) throws IOException {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
		Directory directory = FSDirectory.open(new File("D:/index"));
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_42,
				analyzer);
		IndexWriter it = new IndexWriter(directory, iwc);
		Document doc = new Document();
		doc.add(new org.apache.lucene.document.TextField("info",
				"this is my firdt lucene test", Field.Store.YES));
		it.addDocument(doc);
		it.close();
		directory.close();
	}
}

5、查询索引操作的核心类

IndexReader:读取索引的工具类,常用子类有DirectoryReader

IndexSearch:查询索引的核心类

QueryParser:查询分析器,表示从哪里查用哪个分析器

Query:代表一次查询

TopDocs:封装了匹配情况,比如匹配多少个

ScoreDoc:匹配的数据,里面封装了索引文档的得分和索引ID

6、查询索引


public class SearcheFile {
	public static void main(String[] args) throws Exception {
		Analyzer a = new StandardAnalyzer(Version.LUCENE_42);
		Directory dir =FSDirectory.open(new File("D:/index"));
		IndexReader reader = DirectoryReader.open(dir);
		IndexSearcher is = new IndexSearcher(reader);
		QueryParser parse = new QueryParser(Version.LUCENE_42, "info", a);
		Query query = parse.parse("lucene");
		TopDocs topDocs = is.search(query, 1000);
		System.out.println("总共匹配多少个:"+topDocs.totalHits);
		ScoreDoc[] hits = topDocs.scoreDocs;
		System.out.println("多少条数据:"+hits.length);
		for (ScoreDoc scoreDoc : hits) {
			System.out.println("匹配得分:"+scoreDoc.score);
			System.out.println("文档索引ID:"+scoreDoc.doc);
			Document doc = is.doc(scoreDoc.doc);
			System.out.println(doc.get("info"));
		}
		reader.close();
		dir.close();
	}
	
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值