String Index_Store_Path = "index";
IndexWriter iw = null;
try {
iw = new IndexWriter(Index_Store_Path,new StandardAnalyzer(),true);
iw.setUseCompoundFile(false);
String[] contents = {"ab bc cd de ef fg gh","ab","ab bc","ab bc cd","ab bc cd de",
"ab bc cd de ef","ab bc cd de ef fg","ab bc bc de ef fg gh hi"};
Field f = null;
Document doc = null;
for(int i=0;i<contents.length;i++){
doc = new Document();
f = new Field("bk", contents[i], Field.Store.YES, Field.Index.TOKENIZED);
doc.add(f);
f = new Field("id", "id"+i,Field.Store.YES, Field.Index.TOKENIZED);
doc.add(f);
//通过改变激励因子更改排名 > Sort 不能同时为多个Field指定排序标准 > SortField
if(i== contents.length-1){
doc.setBoost(2f);
}
iw.addDocument(doc);
}
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
iw.close();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
IndexSearcher is = new IndexSearcher(Index_Store_Path);
TermQuery tq = new TermQuery(new Term("bk", "bc"));
//多Field的排序
Sort s = new Sort();
SortField sf = new SortField("id",SortField.STRING, false);
SortField sf1 = new SortField("bk", SortField.STRING,false);
s.setSort(new SortField[] {sf,sf1});
//Query 的Field 和 Sort 的 Field 相互独立
//此Filter非Lucene分析中的过滤器
Hits hits = is.search(tq, new AdvancedSecurityFilter1(), s);
for(int i=0;i<hits.length();i++){
System.out.print(hits.doc(i).get("bk")+"\t\t");
System.out.println(hits.score(i));
System.out.println(is.explain(tq, hits.id(i)).toString());
}
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class AdvancedSecurityFilter extends Filter {
@Override
public BitSet bits(IndexReader reader) throws IOException {
final BitSet bs = new BitSet(reader.maxDoc());
//默认为true
bs.set(0, bs.size()-1);
//代表最高级别??
Term t = new Term("id", "id2");
TermDocs td = reader.termDocs(t);
while(td.next()){
bs.set(td.doc(), false);
}
return bs;
}
}
public class AdvancedSecurityFilter1 extends Filter {
@Override
public BitSet bits(IndexReader reader) throws IOException {
final BitSet bs = new BitSet(reader.maxDoc());
//默认为true
bs.set(0, bs.size()-1);
//代表最高级别??
Term t = new Term("id", "id2");
//使用IndexReader的reader方法并不是对每个情况都适用
//使用IndexSearcher 更能随心所欲的定制过滤的Filed 及 Instance
//并且这种方法封装了底层的API 更为简洁和清晰
IndexSearcher is = new IndexSearcher(reader);
Hits hits = is.search(new TermQuery(t));
for(int i=0;i<hits.length();i++){
bs.set(hits.id(i), false);
}
return bs;
}
}