Lucene学习总结

[size=x-large]一、Lucene 原理[/size]

[size=medium][b]Lucene是一个高效的,基于Java的全文检索库[/b]。

在生活中会遇到各种各样的数据, 而数据可以概括为两种, [b]结构化数据[/b]和[b]非结构化数据[/b]。
1、结构化数据指具有固定格式或有限长度的数据,如数据库,元数据等。
2、非机构化数据指指不定长或无固定格式的数据,如邮件,word文档等。

当我们需要全文检索某个信息,主要有两种方法:
a. [b]顺序扫描法[/b](Serial Scanning):一个一个文件的全文搜索,这种当然是很慢的了。
b. [b]通过索引查找法[/b]:通过对非结构数据进行重新组织,建立索引,再对索引进行查找。而Lucene 就是用的这个原理进行全文检索。

Lucene的全文检索大体分两个过程,索引创建(Indexing)和搜索索引(Search)。
a.[b]索引创建[/b]:将现实世界中所有的结构化和非结构化数据提取信息,创建索引的过程。
b.[b]搜索索引[/b]:就是得到用户的查询请求,搜索创建的索引,然后返回结果的过程。

下面这幅图来自《Lucene in action》,描述了Lucene 的检索过程和全文检索的一般过程。[/size]
[img]http://hi.youkuaiyun.com/attachment/201002/1/3634917_1265048519dbeE.png[/img]

参考自:[url]http://www.cnblogs.com/forfuture1978/archive/2010/06/13/1757479.html[/url]

[size=x-large]二、Lucene例子[/size]
下面是建立索引和查找文件的简单例子
a.建立索引

private static void indexFiles() throws IOException {
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
config.setOpenMode(OpenMode.CREATE_OR_APPEND);

Directory dir = FSDirectory.open(Paths.get("C:\\shuxiang\\tmp\\lucene6"));
IndexWriter writer = new IndexWriter(dir, config);
Document doc = new Document();
Path path = Paths.get("C:\\shuxiang\\tmp\\Edit5");
InputStream newInputStream = Files.newInputStream(path);
InputStreamReader inputStreamReader = new InputStreamReader(newInputStream, StandardCharsets.UTF_8);
Field pathField = new StringField("path", path.toString(), Field.Store.YES);
doc.add(pathField);
TextField field = new TextField("contents", new BufferedReader(inputStreamReader));
doc.add(field);
writer.addDocument(doc);
writer.close();

}


b. 查找文件

private static void searchFile() throws IOException, ParseException {
Directory dir = FSDirectory.open(Paths.get("C:\\shuxiang\\tmp\\lucene6"));
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);

Analyzer analyzer = new StandardAnalyzer();
QueryParser parser = new QueryParser("contents", analyzer);
Query query = parser.parse("92646KHJ4");
System.out.println("Searching for: " + query.toString("contents"));

TopDocs topDocs = searcher.search(query, 100000);
System.out.println(topDocs.totalHits + " total matching documents");
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document hitDoc = searcher.doc(scoreDoc.doc);
System.out.println("hit:" + hitDoc.get("path"));
}
}


Lucene官网有两个很好的例子,如下:
[url]https://lucene.apache.org/core/6_2_1/demo/src-html/org/apache/lucene/demo/IndexFiles.html[/url]

[url]https://lucene.apache.org/core/6_2_1/demo/src-html/org/apache/lucene/demo/SearchFiles.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值