Luncene查询
public class TestQuery {
@Test
//单字段查询
public void query1() throws IOException{
Query query = new TermQuery(new Term("author","张朝"));
testQuery(query);
}
//多字段查询
@Test
public void query2() throws ParseException, IOException{
Version version = Version.LUCENE_44;
Analyzer analyzer = new StandardAnalyzer(version);
String fields[] = {"title","content"};
String keywords = "全文";
QueryParser queryParser = new MultiFieldQueryParser(version,fields, analyzer);
Query query = queryParser.parse(keywords);
testQuery(query);
}
//范围查询
@Test
public void query3() throws IOException{
Query query = NumericRangeQuery.newIntRange("id", 1,5,false,false);
testQuery(query);
}
//通配符查询
@Test
public void query4() throws IOException{
//?代表单个字符,*号代理多个字符
Query query = new WildcardQuery(new Term("title","luce*"));
testQuery(query);
}
//所有查询
@Test
public void query5() throws IOException{
Query query = new MatchAllDocsQuery();
testQuery(query);
}
//模糊查询
@Test
public void query6() throws IOException{
Query query = new FuzzyQuery(new Term("author",""),2);
testQuery(query);
}
//短语查询
@Test
public void query7() throws IOException{
PhraseQuery query = new PhraseQuery();
query.add(new Term("title","lucene"));
query.add(new Term("title","全"));
query.setSlop(10);
testQuery(query);
}
//布尔查询
@Test
public void query8() throws IOException, ParseException{
Query query1 = new TermQuery(new Term("author","张朝"));
Version version = Version.LUCENE_44;
Analyzer analyzer = new StandardAnalyzer(version);
String fields[] = {"title","content"};
String keywords = "全文";
QueryParser queryParser = new MultiFieldQueryParser(version,fields, analyzer);
Query query2 = queryParser.parse(keywords);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(query1,Occur.MUST);
booleanQuery.add(query2,Occur.MUST);
testQuery(booleanQuery);
}
public void testQuery(Query query) throws IOException{
Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));
IndexReader indexReader=DirectoryReader.open(directory);
IndexSearcher indexSearcher=new IndexSearcher(indexReader);
TopDocs topDocs=indexSearcher.search(query,100);
System.out.println("总记录数...=="+topDocs.totalHits);
ScoreDoc scoreDocs []=topDocs.scoreDocs;
for(ScoreDoc scoreDoc:scoreDocs){
int docID=scoreDoc.doc;
Document document=indexSearcher.doc(docID);
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
System.out.println(document.get("author"));
}
}
}