现在在很多都用到全文检索功能,概念就过了,这里我使用到了3个工具包
IKAnalyzer2012FF_u1.jar
lucene-core-4.0.0.jar
lucene-queryparser-4.0.0.jar
创建索引:
/**
* 创建索引
*/
public static void createIndex(){
//创建需要建立索引的目录
File dataDir=new File("F:\\ToolPackage");
if(dataDir.exists()){
//获取文件数组
File[] dataDirs=dataDir.listFiles();
//创建目录
Directory directory=null;
//创建IndexWriter
IndexWriter indexWriter=null;
long startTime=System.currentTimeMillis();//记录开始创建索引时间
try {
directory=FSDirectory.open(new File(getIndexDir()));//打开索引文件存放目录
IndexWriterConfig iwConfig=new IndexWriterConfig(Version.LUCENE_40, new IKAnalyzer(true));//使用粗粒度分词
indexWriter=new IndexWriter(directory, iwConfig);//实例化IndexWriter
for(int i=0;i<dataDirs.length;i++){
//判断是否是文件并且文件后缀是否是.jar格式
if(dataDirs[i].isFile()&&dataDirs[i].getName().endsWith(".jar")){
System.out.println("Index File:"+dataDirs[i].getCanonicalPath());//打印出文件路径
Document document=new Document();//创建文档对象
document.add(new TextField("path", dataDirs[i].getName(),Store.YES));//对文件目录进行分词存储
document.add(new TextField("content", dataDirs[i].getCanonicalPath(),Store.YES));//对文件路径不分词存储
//将文档添加到IndexWriter中
indexWriter.addDocument(document);
}
}
//关闭资源
indexWriter.close();
directory.close();
long endTime=System.currentTimeMillis();//记录创建完成时间
System.out.println(endTime-startTime);
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("目录不存在");
}
}
创建搜索:
/**
* 创建搜索
* @param content
* @return
*/
private static String createSearch(String content){
String result="";
try {
//打开所有文件目录
Directory directory=FSDirectory.open(new File(getIndexDir()));
IndexReader reader=IndexReader.open(directory);//创建索引读取器
IndexSearcher search=new IndexSearcher(reader);//创建索引搜索器
//TermQuery query=new TermQuery(new Term("path",content));//创建分词查询
//使用查询解析器创建Query对象
QueryParser parser=new QueryParser(Version.LUCENE_40, "path", new IKAnalyzer(true));
Query query=parser.parse(QueryParser.escape(content));//传入需要搜索的内容
TopDocs topDocs=search.search(query, 1);//检索得分最高的文档
if(topDocs.totalHits>0){
ScoreDoc[] scoreDoc=topDocs.scoreDocs;//获取分数文档数据
for(ScoreDoc doc:scoreDoc){//遍历分数文档
Document docu=search.doc(doc.doc);//获取文档对象
result=docu.get("content");//输出搜索到的信息
}
}
reader.close();//关闭索引读取器
directory.close();//关闭目录资源
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
索引文件创建在当前目录classes中的
获取创建索引目录路径:
/**
* 获取索引创建目录
* @return
*/
private static String getIndexDir(){
//得到.class文件所在的路径
String classPath=ClassLoader.getSystemClassLoader().getResource("").toString();
if(classPath.startsWith("file:/")){
classPath=classPath.replaceAll("file:/", "");
}
return classPath+"index";
}