搜索引擎学习总结(实战和使用场合)
备注以下代码使用的环境为JDK1.5 ,luence 1.4
1. 代码的解析()
使用场合:创建索引的信息,以便于搜索引擎在适当的时候使用。
/**
* 使用递归索引特定的java文件的信息
* @param writer
* @param dir
* @throws Exception
*/
public static void indexDirectory(IndexWriter writer, File dir)
throws Exception {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
indexDirectory(writer, file);
} else if (file.getName().endsWith(".java")) {
indexFile(writer, file);
}
}
}
/**
* 设置索引文档的方法
* @param writer
* @param f
* @throws Exception
*/
public static void indexFile(IndexWriter writer, File f) throws Exception {
if (f.isHidden() || !f.exists() || !f.canRead()) {
return;
}
System.out.println("indexing ....." + f.getAbsolutePath());
//虚拟的文档的对象的
Document doc = new Document();
//向文档中添加域对象
doc.add(Field.Text("contents", new FileReader(f)));//索引文件的内容
//创建域对象的
//域中添加域对象的
doc.add(Field.Keyword("filename", f.getCanonicalPath()));
//添加索引的文檔的對象
writer.addDocument(doc);
}
/**
* 创建索引文件的
* @param indexDir 存储索引的目录
* @param dataDir 检索的目录文件家
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static int index(File indexDir, File dataDir) throws Exception {
if (!dataDir.exists() || !dataDir.isDirectory()) {
throw new IOException(dataDir
+ "does not exists or is not a direcotry");
}
//创建搜索索引的对象IndexWriter
IndexWriter writer =new IndexWriter(indexDir, new StandardAnalyzer(),
true);
//是否使用一个符合文件
writer.setUseCompoundFile(false);
indexDirectory(writer, dataDir);
int numIndexed = writer.docCount();
//优化索引对象
writer.optimize();
//关闭索引对象
writer.close();
return numIndexed;
}
2.代码使用场合:在搜索引擎检索索引目录的中的信息