您的位置:首页 > 其它

Lucene-搜索方式

2014-03-16 20:49 323 查看
搜索方式、

/**
* 1、关键词查询
* 2、查询所有文档
* 3、范围查询
* 4、通配符查询
* 5、短语查询
* 6、Boolean查询
* @author Administrator
*
*/
public class QueryTest {
/**
* 关键词查询
* 因为没有分词器,所以区分大小写
*/
@Test
public void testTermQuery() throws Exception{
Term term = new Term("title","lucene");
Query query = new TermQuery(term);
this.showData(query);
}

/**
* 查询所有的文档
*/
@Test
public void testAllDocQuery() throws Exception{
Query query = new MatchAllDocsQuery();
this.showData(query);
}

/**
* 通配符查询
* * 代表任意多个任意字符
* ? 任意一个任意字符
*/
@Test
public void testWildCartQuery() throws Exception{
Term term = new Term("title","*.java");
Query query = new WildcardQuery(term);
this.showData(query);
}

/**
* 短语查询
* 所有的关键词对象必须针对同一个属性
* @param query
* @throws Exception
*/
@Test
public void testPharseQuery() throws Exception{
Term term = new Term("title","lucene");
Term term2 = new Term("title","搜索");
PhraseQuery query = new PhraseQuery();
query.add(term,0);
query.add(term2,4);
this.showData(query);
}

/**
* boolean查询
* 各种关键词的组合
* @param query
* @throws Exception
*/
@Test
public void testBooleanQuery() throws Exception{
Term term = new Term("title","北京");
TermQuery termQuery = new TermQuery(term);
Term term2 = new Term("title","美女");
TermQuery termQuery2 = new TermQuery(term2);
Term term3 = new Term("title","北京美女");
TermQuery termQuery3 = new TermQuery(term3);
BooleanQuery query = new BooleanQuery();
query.add(termQuery,Occur.SHOULD);
query.add(termQuery2,Occur.SHOULD);
query.add(termQuery3,Occur.SHOULD);
this.showData(query);
}

/**
* 范围查询
* @param query
* @throws Exception
*/
@Test
public void testRangeQuery() throws Exception{
Query query = NumericRangeQuery.newLongRange("id", 5L, 10L, true, true);
this.showData(query);
}

private void showData(Query query) throws Exception{
IndexSearcher indexSearcher = new IndexSearcher(LuceneUtils.directory);
TopDocs topDocs = indexSearcher.search(query, 25);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
List<Article> articleList = new ArrayList<Article>();
for(ScoreDoc scoreDoc:scoreDocs){
Document document = indexSearcher.doc(scoreDoc.doc);
Article article = DocumentUtils.document2Article(document);
articleList.add(article);
}

for(Article article:articleList){
System.out.println(article.getId());
System.out.println(article.getTitle());
System.out.println(article.getContent());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: