今天星期天抽空写了一个关于创建索引和搜索的简单示例,描述了创建索引和搜索的每一个步骤,以后慢慢详细介绍每个细节的实现,废话不多说了,进入重点
1.用到的Jar:
2.创建索引和搜索代码如下:
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.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;
import java.io.File;
import java.io.FileReader;
/**
* 创建索引和搜索
* Created by Administrator on 14-3-12.
*/
public class HelloLucenes {
/**
* 创建索引
*/
public void createIndex(){
try
{
//1.创建Directory
Directory directory=FSDirectory.open(new File("d:/lucene/index0"));
//2.创建IndexWriter
IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_47, new StandardAnalyzer(Version.LUCENE_47));
IndexWriter writer=new IndexWriter(directory,iwc);
//3.创建Document对象
Document document=null;
//4.为Document添加Field
File file=new File("d:/lucene/data");
for(File f:file.listFiles())
{
document=new Document();
document.add(new StringField("path", f.getAbsolutePath(), Field.Store.YES));
document.add(new StringField("filename",f.getName(), Field.Store.YES));
document.add(new TextField("content",new FileReader(f)));
//5.通过IndexWriter添加文档到索引中
writer.addDocument(document);
}
writer.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* 创建搜索
*/
public void createSearch()
{
try{
//1、创建Directory
Directory directory= FSDirectory.open(new File("d:/lucene/index0"));
//2、创建IndexReader
IndexReader reader=DirectoryReader.open(directory);
//3、根据IndexReader创建IndexSearch
IndexSearcher searcher=new IndexSearcher(reader);
//4、创建搜索的Query(赤岸感觉Parser来去顶要搜索的文件的内容,第二个参数标示搜索的域)
QueryParser parser=new QueryParser(Version.LUCENE_47,"content",new StandardAnalyzer(Version.LUCENE_47));
Query query=parser.parse("father");
//5、根据search搜索并且返回TopDocs
TopDocs tds=searcher.search(query,10);
//6、根据TOpDocs获取ScoreDoc对象
ScoreDoc[] sds=tds.scoreDocs;
for(ScoreDoc sd:sds)
{
//6、根据search和ScordDoc对象获取具体的Document对象
Document d=searcher.doc(sd.doc);
//8、根据Document对象获取需要的值
System.out.println(d.get("filename")+"["+d.get("path")+"]");
}
//9、关闭reader
reader.close();
}catch (Exception ex)
{
}
}
}
3.创建测试类代码如下:
import org.junit.Test;
/**
* 单元测试类
* Created by Administrator on 14-3-12.
*/
public class HelloLucenesTest {
@Test
public void hello(){
HelloLucenes hl=new HelloLucenes();
hl.createIndex();
}
@Test
public void search(){
HelloLucenes hl=new HelloLucenes();
hl.createSearch();
}
}
4.目标数据文件如下图所示:
5.运行创建索引方法的结果如下图:
6.运行搜索方法结果如下: