只需两步实现自定义过滤器
一、
package search;
import org.apache.lucene.index.AtomicReader;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.OpenBitSet;
import java.io.IOException;
/**
* 自定义过滤器,过滤文档大小
* Created with IntelliJ IDEA.
* User: wxshi
* Date: 15-2-10
* Time: 下午7:54
* To change this template use File | Settings | File Templates.
*/
public class MyFilters extends Filter {
private String fieldKey;
private String fieldValue;
//定义域:域值
public MyFilters(String fieldKey, String fieldValue)
{
super();
this.fieldKey=fieldKey;
this.fieldValue=fieldValue;
}
//重写过滤细节,返回过滤结果
@Override
public DocIdSet getDocIdSet(AtomicReaderContext atomicReaderContext, Bits bits) throws IOException {
AtomicReader reader = atomicReaderContext.reader();
OpenBitSet bitSet = new OpenBitSet(reader.numDocs()); //获取搜索的文档总数
Term term = new Term(this.fieldKey,this.fieldValue); //过滤的域条件
DocsEnum docEnum = reader.termDocsEnum(term); //获取 DocsEnum,返回过滤的文档,并枚举
for(int i=0;i<reader.numDocs();i++){
bitSet.set(docEnum.nextDoc()); //将过滤返回的文档加入返回的集合
}
return bitSet; //To change body of implemented methods use File | Settings | File Templates.
}
}
二、
package search;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;
/**
* 自定义查询器,通过覆盖制定查询方法实现自定义查询
* 本例通过覆盖通配符和模糊查询而禁用此类查询,提高系统性能,其他查询方法不变
*
* Created with IntelliJ IDEA.
* User: wxshi
* Date: 15-2-26
* Time: 上午11:33
* To change this template use File | Settings | File Templates.
*/
public class MyQueryParser extends QueryParser {
public MyQueryParser(String f, Analyzer a) {
super(f, a);
}
@Override
protected Query getWildcardQuery (String field, String term) throws ParseException {
throw new ParseException("系统禁用通配符查询");
//return super.getWildcardQuery(f, term);
}
@Override
protected Query getFuzzyQuery (String field, String term,float s) throws ParseException {
throw new ParseException("系统禁用模糊查询");
//return super.getWildcardQuery(f, term);
}
//覆盖范围查询
@Override
protected Query getRangeQuery (String field, String part1,String part2,boolean startInclude,boolean endInclude) throws ParseException {
if("size".equals(field)){ //文件大小
return NumericRangeQuery.newIntRange(field, Integer.parseInt(part1), Integer.parseInt(part2), startInclude, endInclude);
}else if("time".equals(field)){ //日期
String dateType = "yyyy-MM-dd";
Pattern rex = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
if(rex.matcher(part1).matches()&&rex.matcher(part2).matches()) {
SimpleDateFormat formate = new SimpleDateFormat(dateType);
try {
long start = formate.parse(part1).getTime();
long end = formate.parse(part2).getTime();
return NumericRangeQuery.newLongRange(field, start,end, startInclude, endInclude);
} catch (java.text.ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return newRangeQuery( field, part1, part2, startInclude, endInclude);
}
}
三、搜索测试
package search;
import myscore.MyCustomScoreQuery;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;
import utils.ConstantUtil;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: wxshi
* Date: 15-2-6
* Time: 下午2:02
* To change this template use File | Settings | File Templates.
*/
public class MYSearch {
private IndexSearcher indexSearch = null;
private Query query = null;
private static Filter filter = null;
private static CachingWrapperFilter cachingWrapperFilter;// 缓存过滤结果
//封装IndexSearch对象
public MYSearch(){
try {
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(ConstantUtil.INDEX_STORE_PATH)));
indexSearch = new IndexSearcher(reader);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
//定义自己的filter
public void getFilter() {
//以包含指定项的文档进行匹配
//filter = new FieldCacheTermsFilter("content", new String[] {"你"});
//以特殊前缀开始的项的文档进行匹配
//filter = new PrefixFilter(new Term("title", "文件"));
//过滤字符开头从a到i的内容
//filter = new TermRangeFilter("content", new BytesRef("a"), new BytesRef("m"), true, true);
//过滤域从XX开头到XX结尾的文档
//filter = TermRangeFilter.newStringRange("title", "1", "txt", true, true);
//过滤文档大小XX~XX的文档
//filter = NumericRangeFilter.newLongRange("size", 1L, 50L, true, true);
//通过包装query对结果再进行过滤,相当于二次搜索
//filter = new QueryWrapperFilter(new WildcardQuery(new Term("content","历史")));
//自定义过滤器
filter = new MyFilters("title","文件1.txt");
// 缓存过滤器,提高搜索性能 (此过滤器会缓存过滤结果)
cachingWrapperFilter = new CachingWrapperFilter(filter);
}
//搜索
public TopDocs search(String filed,String keyWord){
try {
Analyzer analyzer = new IKAnalyzer();
//在field域中查询
QueryParser parser = new MyQueryParser(filed,analyzer);
query = parser.parse(keyWord); //传入的搜索词
MyCustomScoreQuery myQuery = new MyCustomScoreQuery(query);
//使用评分排序
// TopDocs results = indexSearch.search(myQuery,5,Sort.RELEVANCE);
//使用docId进行排序
// TopDocs results = indexSearch.search(myQuery,5,Sort.INDEXORDER);
//按文件大小来排
// TopDocs results = indexSearch.search(myQuery,5,new Sort(new SortField("size",SortField.Type.LONG)));
//按文件名来排 ,true代表降序
// TopDocs results = indexSearch.search(myQuery,5,new Sort(new SortField("title",SortField.Type.STRING,true)));
//按多个域进行排序,先按评分,再按标题,再按大小
// TopDocs results = indexSearch.search(myQuery,5,new Sort(SortField.FIELD_SCORE,new SortField("title",SortField.Type.STRING),new SortField("size",SortField.Type.LONG)));
//不使用自定义排序,此时会根据评分排序,且能获取分数
TopDocs results = indexSearch.search(myQuery,filter,5);
return results;
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return null;
}
//解析搜索结果
public void printResult(TopDocs results){
ScoreDoc docs[] = results.scoreDocs;
if(docs.length>0){
for(int i=0;i<docs.length;i++){
try {
Document doc = indexSearch.doc(docs[i].doc);
int j = i+1;
System.out.print("这是第" + j + "个检索到的结果,文件路径为:");
System.out.println(doc.get("path"));
System.out.print("这是第" + j + "个检索到的结果,文件标题为:");
System.out.println(doc.get("title"));
System.out.print("这是第" + j + "个检索到的结果,文件内容为:");
System.out.println(doc.get("content"));
System.out.print("这是第" + j + "个检索到的结果,文件大小为:");
System.out.println(doc.get("size"));
System.out.println("评分为:" + docs[i].score);
System.out.println("--------------------------------------------");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}else{
System.out.println("没有搜索结果");
}
}
}