你好,游客 登录 注册 搜索
背景:
阅读新闻

Lucene入门基础教程

搜索方式

[日期:2014-06-08] 来源:Linux社区  作者:xinxinqiu [字体:大 中 小]

搜索方式

/**
 * 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());
  }
 }
}

linux
【内容导航】
第1页:简介 第2页:准备Lucene的开发环境
第3页:保持数据库与索引库的同步 第4页:indexWriter
第5页:与索引库的交互 第6页:分词器
第7页:分页 第8页:搜索方式
第9页:排序+高亮 第10页:常用API
相关资讯       Lucene  Lucene教程  Lucene简介 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述���款