过滤器Filter的使用

  categories:搜索资料  author:

来源:互联网

要过滤一部分搜索内容就要用到BitSet,何为BitSet呢?即一个“位集合”队列,当lucene返回结果时,会首先遍历BitSet,仅将那些值为true的文档返回。而且要引入新的API(每次学到新内容时,都要上网查,太麻烦了,而且这个时必须的,浪费时间)

import java.util.BitSet;

然后新建一个AdvancedSecurityFilter类:

public class AdvancedSecurityFilter extends Filter
{
public static final int SECURITY_ADVANCED=0;
public BitSet bits(IndexReader reader) throws IOException
{
final BitSet bits=new BitSet(reader.maxDoc());
bits.set(0,bits.size()-1);

Term term=new Term(“securitylevel”,SECURITY_ADVANCED+””);

TermDocs termDocs=reader.termDocs(term);
while(termDocs.next())
{
bits.set(termDocs.doc(),false);
}
return bits;
}
}

当时我写了这段程序,结果public BitSet bits(IndexReader reader) throws IOException一直报错,我看了又看,想了又想,没错啊,你猜怎的?忘了写返回值了,郁闷!记着 BitSet类型一定要写返回值!!!

既然调试好了,就把打印的代码写出来吧

 

public static void printFilter(String path)throws IOException{
Term begin=new Term(“publishdate”,”1999-01-01″);
Term end=new Term (“publishdate”,”1999-10-15″);

RangeQuery q=new RangeQuery(begin,end,true);

IndexSearcher searcher=new IndexSearcher(path);
Hits hits=searcher.search(q,new AdvancedSecurityFilter());

for(int i=0;i<hits.length();i++)
{
Document doc=hits.doc(i);

System.out.println(“书号:”);
System.out.println(doc.get(“bookNumber”));
System.out.println(“书名:”);
System.out.println(doc.get(“bookname”));
System.out.println(“出版日期:”);
System.out.println(doc.get(“publishdate”));
System.out.println(“安全级别”);
int level=Integer.parseInt(doc.get(“securitylevel”));
switch(level)
{
case SECURITY_ADVANCED:
System.out.println(“高级”);
break;
case SECURITY_MIDDLE:
System.out.println(“中级”);
break;
case SECURITY_NORMAL:
System.out.println(“一般”);
break;
}
System.out.println(“====================”);
}
}

上面的层次比较清晰,再看看下面的代码,也行哦

public static void printFilter(String path)throws IOException
{
Term begin=new Term(“publishdate”,”1999-01-01″);
Term end=new Term (“publishdate”,”1999-10-15″);

RangeQuery q=new RangeQuery(begin,end,true);

IndexSearcher searcher=new IndexSearcher(path);
Hits hits=searcher.search(q,new Filter(){
public BitSet bits(IndexReader reader)throws IOException
{
final BitSet bits=new BitSet(reader.maxDoc());
bits.set(0,bits.size()-1);

Term term=new Term(“securitylevel”,SECURITY_ADVANCED+””);

TermDocs termDocs=reader.termDocs(term);
while(termDocs.next())
{
bits.set(termDocs.doc(),false);
}
return bits;
}
}
);

for(int i=0;i<hits.length();i++)
{
Document doc=hits.doc(i);

System.out.println(“书号:”);
System.out.println(doc.get(“bookNumber”));
System.out.println(“书名:”);
System.out.println(doc.get(“bookname”));
System.out.println(“出版日期:”);
System.out.println(doc.get(“publishdate”));
System.out.println(“安全级别”);
int level=Integer.parseInt(doc.get(“securitylevel”));
switch(level)
{
case SECURITY_ADVANCED:
System.out.println(“高级”);
break;
case SECURITY_MIDDLE:
System.out.println(“中级”);
break;
case SECURITY_NORMAL:
System.out.println(“一般”);
break;
}
System.out.println(“====================”);
}
}

直接在使用Hits时加入过滤程序,查了一下资料,原来这就是传说中的覆盖(override)



快乐成长 每天进步一点点