本帖最后由 gefieder 于 2015-4-19 22:40 编辑
问题导读:
1、如何使用lucene对硬盘上的文件建立索引?
2、如何在索引文件中查询一个词?
3、索引过程中的几个核心类是?它们的作用是?
接上篇:一步一步学lucene——(第一步:概念篇)
在上面的篇幅中我们已经了解到了lucene,及lucene到底是做什么的,什么情况下才能够使用lucene,下面我们就结合一个例子来详细说明一下lucene的API,看看lucene是如何工作的。
lucene的下载其实这个很简单了,直接到baidu或者google上搜索一下,一般情况下第一个就是我们要的链接。下边给出lucene下载的链接:
http://lucene.apache.org/
图:lucene下载主页面
配置环境我们下面要做很多的测试,会建立很多的测试工程,如果一个一个手动的添加jar包会非常的麻烦,那么我们就需要配置eclipse环境。
打开eclipse,选择windows->preferences->java->build path->user libraries
将我们上边下载后的lucene中的包全部加载到这个用户变量中。
图:eclipse中加入的用户变量
建立索引下面这个程序就是读取指定文件夹下的文件并且将文件生成索引的过程,它有两个参数,一个是要索引的文件路径,一个是索引存放的路径。
我们将文件放到我们硬盘的目录上,然后通过程序建立索引。
索引程序如下:
- public class Indexer {
-
- public static void main(String[] args) throws Exception {
- if (args.length != 2) {
- throw new IllegalArgumentException("Usage: java "
- + Indexer.class.getName() + " <index dir> <data dir>");
- }
- String indexDir = args[0]; // 1
- String dataDir = args[1]; // 2
-
- long start = System.currentTimeMillis();
- Indexer indexer = new Indexer(indexDir);
- int numIndexed;
- try {
- numIndexed = indexer.index(dataDir, new TextFilesFilter());
- } finally {
- indexer.close();
- }
- long end = System.currentTimeMillis();
-
- System.out.println("Indexing " + numIndexed + " files took "
- + (end - start) + " milliseconds");
- }
-
- private IndexWriter writer;
-
- public Indexer(String indexDir) throws IOException {
- Directory dir = FSDirectory.open(new File(indexDir));
- writer = new IndexWriter(dir, // 3
- new StandardAnalyzer( // 3
- Version.LUCENE_30),// 3
- true, // 3
- IndexWriter.MaxFieldLength.UNLIMITED); // 3
- }
-
- public void close() throws IOException {
- writer.close(); // 4
- }
-
- public int index(String dataDir, FileFilter filter) throws Exception {
-
- File[] files = new File(dataDir).listFiles();
-
- for (File f : files) {
- if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()
- && (filter == null || filter.accept(f))) {
- indexFile(f);
- }
- }
-
- return writer.numDocs(); // 5
- }
-
- private static class TextFilesFilter implements FileFilter {
- public boolean accept(File path) {
- return path.getName().toLowerCase() // 6
- .endsWith(".txt"); // 6
- }
- }
-
- protected Document getDocument(File f) throws Exception {
- Document doc = new Document();
- doc.add(new Field("contents", new FileReader(f))); // 7
- doc.add(new Field("filename", f.getName(), // 8
- Field.Store.YES, Field.Index.NOT_ANALYZED));// 8
- doc.add(new Field("fullpath", f.getCanonicalPath(), // 9
- Field.Store.YES, Field.Index.NOT_ANALYZED));// 9
- return doc;
- }
-
- private void indexFile(File f) throws Exception {
- System.out.println("Indexing " + f.getCanonicalPath());
- Document doc = getDocument(f);
- writer.addDocument(doc); // 10
- }
-
- }
复制代码
然后在工程上点击右键Run->Run configuration,新建一个Java Application,输入两个参数一个是索引目录,一个是文件存放目录
图:配置运行界面
运行后可以行到分析结果,当然目录中索引的内容不同得到的结果也就会不同。
图:索引txt文件时输出
根据索引查询因为这里边还没涉及到中文的部分,所以我们查询所有文档中包括"RUNNING"的文档。
程序内容如下:
- public class Searcher {
-
- public static void main(String[] args) throws IllegalArgumentException,
- IOException, ParseException {
- if (args.length != 2) {
- throw new IllegalArgumentException("Usage: java "
- + Searcher.class.getName() + " <index dir> <query>");
- }
-
- String indexDir = args[0]; // 1
- String q = args[1]; // 2
-
- search(indexDir, q);
- }
-
- public static void search(String indexDir, String q) throws IOException,
- ParseException {
-
- Directory dir = FSDirectory.open(new File(indexDir)); // 3
- IndexSearcher is = new IndexSearcher(dir); // 3
-
- QueryParser parser = new QueryParser(Version.LUCENE_30, // 4
- "contents", // 4
- new StandardAnalyzer( // 4
- Version.LUCENE_30)); // 4
- Query query = parser.parse(q); // 4
- long start = System.currentTimeMillis();
- TopDocs hits = is.search(query, 10); // 5
- long end = System.currentTimeMillis();
-
- System.err.println("Found " + hits.totalHits + // 6
- " document(s) (in " + (end - start) + // 6
- " milliseconds) that matched query '" + // 6
- q + "':"); // 6
-
- for (ScoreDoc scoreDoc : hits.scoreDocs) {
- Document doc = is.doc(scoreDoc.doc); // 7
- System.out.println(doc.get("fullpath")); // 8
- }
-
- is.close(); // 9
- }
- }
复制代码
同上操作,配置新的Java Application,如下图:
图:配置查询参数
点击运行,可以得到运行结果。
也就是我们上面索引的文件,当然,随着文件的多少及大小,速度会不同,这里只是一个演示程序,你可以根据你本身的程序自行设置查询条件。
索引过程中的几个核心类IndexWriter
IndexWriter是索引过程的核心组件。用于创建一个新的索引并把文档加到已有的索引中去,也可以向索引中添加、删除和更新被索引文档的信息。
Directory
Directory类描述了Lucene索引的存放位置。
Analyzer
Analyzer是分词器接口,文本文件在被索引之前,需要经过Analyzer处理。常用的中文分词器有庖丁、IKAnalyzer等。
Document
Document对象代表一组域(Field)的集合。其实说白了就是文件,可能是文本文件,word或者pdf等。
Field
Field就是每个文档中包含的不同的域。
lucene构建索引的流程图如下:
图:lucene构建索引流程
搜索过程中的几个核心类IndexSearcher
IndexSearcher是对前边IndexWriter创建的索引进行搜索。
Term
Term对象是搜索功能的基本单元,跟Field对象非常类似,可以放入我们查询的条件。
Query
Query就是Lucene给我们的查询接口,它有很多的子类,我们可以基于这些进行功能丰富的查询。
TermQuery
TermQuery是Lucene提供的最基本的查询类型。
TopDocs
TopDocs类是一个简单的指针容器,指针一般指向前N个排名的搜索结果,搜索结果即匹配查询条件的文档。
图:lucene查询请求流程
[源码下载]
资料来源:http://www.cnblogs.com/skyme/archive/2012/07/31/2615054.html
|