搜索
1.创建搜索的索引目录
Directory directory = FSDirectory.open(new File("E:/Lucene/demo"));
2.创建搜索器
IndexSearcher searcher = IndexReader.open(directory);
3.创建搜索条件
Query query = new TermQuery(new Term(field,value)); //索引域field中含有值value的内容
4.执行搜索
TopDocs topDocs = searcher.search(query,count); //根据searcher搜索并返回TopDocs 返回count条
5.根据TopDocs获取ScoreDoc对象数组
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
6.遍历ScoreDoc数组获取Document对象
for (ScoreDoc sd : scoreDocs) {
Document doc = searcher.doc(sd.doc);
String name = doc.get("name");
}
7.关闭IndexSearcher
searcher.close();
重难点:
查询条件的选择:
1.精确查询,索引域field=value的内容
Query query = new TermQuery(new Term(field,value));
2.模糊查询字符串,索引域field中以start开始end结尾的内上下区间都包括的内容
Query query = new TermRangeQuery(field, start, end, true, true);
3.模糊查询数值,索引域field中以start开始end结尾的内上下区间都包括的内容
Query query = NumericRangeQuery.newFloatRange(field, min, max, true, true); //newDoubleRange/newIntRange/newLongRange
4.模糊查询以X为前缀的内容,索引域field中以value开头的内容
Query query = new PrefixQuery(new Term(field,value));
5.模糊查询—*通配符查询,索引域field中=*value*的内容,分三种情况,*value/value*/*value*
Query query = new WildcardQuery(new Term(field,value));
6.
单例的Directory和IndexReader和IndexSearcher
private static IndexReader reader;
private static Directory directory;
static{
try {
//索引目录
directory = FSDirectory.open(new File("E:/Lucene/demo"));
//读取器
reader = IndexReader.open(directory);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取查询器
* @return
* @author:qiuchen
*/
public static IndexSearcher getSearcher(){
try {
if(reader == null){
reader = IndexReader.open(directory);
}else{
//如果reader发生变化,重新创建
IndexReader ir = IndexReader.openIfChanged(reader);
if(ir != null){
reader.close(); //把原来的reader关闭
reader = ir; //重新给reader赋值
}
}
return new IndexSearcher(reader);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭查询器
* @author:qiuchen
*/
public static void closeSearch(IndexSearcher searcher){
try {
if(searcher != null)
searcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}