Lucene

本文是Lucene全文检索的一个简单例子,想详细了解请自己搜阅其他资料.

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
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 org.wltea.analyzer.lucene.IKAnalyzer;

public class Test {
//文件路劲
private String fileResource="E:/ResourceOneBizFoundation5.0.5/workspace/testa/modules/aa/resources/fileResources/a.txt";
//索引路劲
private String indexResource="E:/ResourceOneBizFoundation5.0.5/workspace/testa/modules/aa/resources/indexResources";
//定义分词器(当前采用IK分词器)
Analyzer aly=new IKAnalyzer();
public void createIndex() throws Exception{
//创建索引目录
Directory dt=FSDirectory.open(new File(indexResource));
//创建分词器(索引目录,分词器设置(lucene版本,分词器))
IndexWriter iw=new IndexWriter(dt,new IndexWriterConfig(Version.LUCENE_CURRENT,aly));
//IO流解析文件
File ifl = new File(fileResource);
//lucene支持从reader读取数据,所以采用了reader流
Reader fr=new FileReader(ifl);

//设置索引类型
FieldType ft = new FieldType();
ft.setIndexed(true);//是否进行索引
ft.setStored(false);//是否存储    reader类型不能进行存储
ft.setTokenized(true);//是否分词
ft.setOmitNorms(true);//节省内存模式

Field field = new Field("content",fr,ft);//处理这个文件
StringField sf = new StringField("path",ifl.getAbsolutePath(),Store.YES);
Document doc=new Document();
doc.add(field);//将content属性放入document
doc.add(sf);//将path属性放入document
iw.addDocument(doc);//写入索引目录
iw.forceMerge(1);// 强制写入索引目录里
iw.close();
}


public void selectSource()throws Exception{
//创建索引目录
Directory dt=FSDirectory.open(new File(indexResource));
IndexReader ir=IndexReader.open(dt);
//查询索引的方法
IndexSearcher is=new IndexSearcher(ir);
//需要的query
QueryParser parser=new QueryParser(Version.LUCENE_CURRENT,"content",aly);
Query query = parser.parse("IT案例");
//执行查询,并且设置查询的最大数量
TopDocs td = is.search(query, 1000);
//查询到的命中数
System.out.println(td.totalHits);
//查询出query的结果集
ScoreDoc[] sd = td.scoreDocs;
for(ScoreDoc ss : sd){
//文档编号
int doc = ss.doc;
//根据编号查询文档
Document docu = is.doc(doc);
System.out.println(docu.getField("path"));
}
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Test t=new Test();
//t.createIndex();
t.selectSource();
}

}

你可能感兴趣的:(Lucene,全文检索)