最近在研究全文检索,看到lucene这个项目很不错。于是拿来把玩。今天成功体验了下检索。拿出来与大家分享下:
lucene项目官网:http://lucene.apache.org/
lucene版本:lucene-3.0.3.zip最新版本已经到3.5了,但是最新版本里没有我们此次体验的demo
先去找3.0.2版本,版本不好找哦,属于早期的代码了。现在提供人人的镜像下载地址:http://labs.renren.com/apache-mirror/lucene/java/3.0.3/
下载倒数第二项lucene-3.0.3.zip 就可以。
解压缩之后会看到如下文件夹:
得到API之后,我们就可以建立项目了。打开eclipse如果不熟悉可以去查找相关资料,网上很多关于eclipse的资料。
新建java project
新建包org.apache.lucene.demo
将lucene-3.0.3\src\demo\org\apache\lucene\demo
下的所有文件添加到项目包下。得到如下目录项目
运行IndexFiles类。选择run as config 在arguments参数填入需要检索的目录。例如:D:\Data
运行结果如下。将目录下文件全部检索。然后可以体验搜索了。
选择SearchFiles运行。输入要检索的关键字。比如‘滕州’
就可以运行查询结果。
可以根据它这个自己写一个检索
package com.xinzhou.Index;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.demo.FileDocument;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class FilesIndex
{
static final File INDEX_DIR = new File("XinZhouIndex");
/** Index all text files under a directory. */
public void IndexDocFiles(String indexSourcePath)
{
String usage = "请输入要索引文件的路径";
if (indexSourcePath.length() == 0)
{
System.err.println("Usage: " + usage);
System.exit(1);
}
final File docDir = new File(indexSourcePath);
if (!docDir.exists() || !docDir.canRead())
{
System.out
.println("Document directory '"
+ docDir.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try
{
IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_DIR),
new StandardAnalyzer(Version.LUCENE_CURRENT), true,
IndexWriter.MaxFieldLength.LIMITED);
System.out.println("Indexing to directory '" + INDEX_DIR + "'...");
indexDocs(writer, docDir);
System.out.println("Optimizing...");
writer.optimize();
writer.close();
Date end = new Date();
System.out.println(end.getTime() - start.getTime()
+ " total milliseconds");
} catch (IOException e)
{
System.out.println(" caught a " + e.getClass()
+ "\n with message: " + e.getMessage());
}
}
static void indexDocs(IndexWriter writer, File file) throws IOException
{
// do not try to index files that cannot be read
if (file.canRead())
{
if (file.isDirectory())
{
String[] files = file.list();
// an IO error could occur
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
indexDocs(writer, new File(file, files[i]));
}
}
} else
{
System.out.println("adding " + file);
try
{
writer.addDocument(FileDocument.Document(file));
}
// at least on windows, some temporary files raise this
// exception with an "access denied" message
// checking if the file can be read doesn't help
catch (FileNotFoundException fnfe)
{
;
}
}
}
}
// 测试
public static void main(String[] args)
{
FilesIndex fileIndex = new FilesIndex();
fileIndex.IndexDocFiles("d:/data");
}
}
也可以写一个查询程序。这样自己就可以编写全文检索程序了。怎么样,很简单吧
java多好~~