您的位置:首页 > 其它

lucene介绍及入门实例

2011-08-10 23:09 417 查看
介绍:

1.Lucene是一个强大的java搜索库,他能让你很轻易将搜索功能加入到任何程序里面。

2.Lucene是一款高性能,可扩展的信息检索(IR)工具库,并不是一个完整的搜索程序(Nutch是基于Lucene的一个优秀的开源的web搜索引擎),它只是专注与文件索引和搜索功能,充当搜索程序中核心索引和搜索模块而已。

3.Lecene不关注你的数据来源,只要是能转为文本即可。也就是说你可以索引和搜索存储在文件中的如下数据:远程web服务器上的网页,本地文件系统中的文档。简单的文本文件,Word文档,XML文档。HTML文档或者PDF文档,或者其他能够从中提取出文本信息的数据格式。

下面是一个入门例子:基于最新版本的lucene3.3

1.建立索引

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
* @author lzy
* @version 1.0
*/

public class Indexer1 {

public static void main(String[] args)throws Exception {
//		if(args.length<2){
//			throw new Exception("长度不够!");
//		}
File indexDir=new File("F:\\indexDir");
File sourceDir=new File("F:\\jar\\lucene\\LIAsourcecode\\lia2e\\src\\lia\\meetlucene\\data");
long startTime=System.currentTimeMillis();
Indexer1 index=new Indexer1(indexDir);
int count=index.index(sourceDir, new MyFileFilter());
index.close();
long endTime=System.currentTimeMillis();
System.out.println("一共创建了"+count+"个索引!");
System.out.println("花费了"+(endTime-startTime)+"毫秒!");

}
private IndexWriter indexWriter;

public Indexer1(File indexDir) throws IOException{
//创建索引文件目录
Directory directory=FSDirectory.open(indexDir);
IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_33,
new StandardAnalyzer(Version.LUCENE_33));
indexWriter = new IndexWriter(directory,config);
}

public int index(File sourceDir,FileFilter fileFilter) throws IOException{
File[] files=sourceDir.listFiles();
for (int i = 0; i < files.length; i++) {
File f=files[i];
if(!f.isDirectory() && f.canRead() && !f.isHidden() && f.exists() && fileFilter.accept(f)){
indexFile(f);
}
}
System.out.println(indexWriter.maxDoc()); //最大索引数;
indexWriter.optimize(); //使最优化
return indexWriter.numDocs();  //生成的索引数
}

//索引文件
public void indexFile(File file) throws IOException{
String fileName=file.getCanonicalPath();   //文件名
System.err.println("被索引的文件:"+fileName);
Document doc=getDoc(file);
indexWriter.addDocument(doc);
}

//创建索引文档
public Document getDoc(File file) throws IOException{
Document doc=new Document();
doc.add(new Field("context",new FileReader(file)));
doc.add(new Field("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED)); //存储不分词
doc.add(new Field("fullpath",file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
return doc;
}

public void close() throws CorruptIndexException, IOException{
indexWriter.close();
}

//后缀为txt的文件
private static class MyFileFilter implements FileFilter{

@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}

}
}


2.搜索索引

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
* @author lzy
* @version 1.0
*/

public class Searcher1 {

public static void main(String[] args) throws IOException, ParseException {
File indexDir=new File("F:\\indexDir");
searcher(indexDir,"Copyright");
}

public static  void searcher(File indexDir,String keyword) throws IOException, ParseException{
//打开索引目录
Directory directory=FSDirectory.open(indexDir);
IndexSearcher indexS=new IndexSearcher(directory);

//解析查询字符串
QueryParser parse=new QueryParser(Version.LUCENE_33, "context", new StandardAnalyzer(Version.LUCENE_33));
Query query=parse.parse(keyword);
long start=System.currentTimeMillis();
TopDocs docs= indexS.search(query, 20);  //搜索索引  取前20条找到的记录
long end=System.currentTimeMillis();

System.err.println("总共找到了"+docs.totalHits+"条记录。一共花费了"+(end-start)+"毫秒!");

//返回匹配文本
ScoreDoc[] scoreDocs=docs.scoreDocs;

for(ScoreDoc sd:scoreDocs){
//转化为文本
//System.out.print(sd.doc) 文件位置;
Document doc=indexS.doc(sd.doc);
for (Fieldable fa : doc.getFields()) {
//System.out.println(fa.name());
String value = doc.get(fa.name());
//				System.out.println(value);
}
System.out.println(doc.get("filename"));
}
indexS.close();
}
}
在本例子中每个被索引的文件都很小,但要花费约0.8秒的时间来索引一组文本文件。这个事实会令你很惊讶...索引的吞吐量很重要,后面有详细介绍这块的.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: