lucene学习之二boolean搜索(相当于SQL中的or、and等)

public class BooleanQueryTest extends TestCase {
  public void testAnd() throws Exception {
    TermQuery searchingBooks =
      new TermQuery(new Term("subject","search"));  //#1

    Query books2010 =                       //#2
      NumericRangeQuery.newIntRange("pubmonth", 201001,       //#2
                                    201012,                   //#2
                                    true, true);                //#2

    BooleanQuery searchingBooks2010 = new BooleanQuery();              //#3
    searchingBooks2010.add(searchingBooks, BooleanClause.Occur.MUST);  //#3
    searchingBooks2010.add(books2010, BooleanClause.Occur.MUST);       //#3

    Directory dir = TestUtil.getBookIndexDirectory();
    IndexSearcher searcher = new IndexSearcher(dir);
    TopDocs matches = searcher.search(searchingBooks2010, 10);

    assertTrue(TestUtil.hitsIncludeTitle(searcher, matches,
                                 "Lucene in Action, Second Edition"));
    searcher.close();
    dir.close();
  }

/*
#1 Match books with subject 鈥渟earch鈥�#2 Match books in 2004
#3 Combines two queries
*/

  public void testOr() throws Exception {
    TermQuery methodologyBooks = new TermQuery(                       // #1
               new Term("category",                                   // #1
                 "/technology/computers/programming/methodology"));   // #1

    TermQuery easternPhilosophyBooks = new TermQuery(                 // #2
        new Term("category",                                          // #2
            "/philosophy/eastern"));                                  // #2

    BooleanQuery enlightenmentBooks = new BooleanQuery();             // #3
    enlightenmentBooks.add(methodologyBooks,                          // #3
                           BooleanClause.Occur.SHOULD);               // #3
    enlightenmentBooks.add(easternPhilosophyBooks,                    // #3
                           BooleanClause.Occur.SHOULD);               // #3

    Directory dir = TestUtil.getBookIndexDirectory();
    IndexSearcher searcher = new IndexSearcher(dir);
    TopDocs matches = searcher.search(enlightenmentBooks, 10);
    System.out.println("or = " + enlightenmentBooks);

    assertTrue(TestUtil.hitsIncludeTitle(searcher, matches,
                                         "Extreme Programming Explained"));
    assertTrue(TestUtil.hitsIncludeTitle(searcher, matches,
                                         "Tao Te Ching \u9053\u5FB7\u7D93"));
    searcher.close();
    dir.close();
  }

  /*
#1 Match 1st category
#2 Match 2nd category
#3 Combine
   */
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值