2011-01-06 84 views
3

我剛剛開始使用Hibernate Search。我是用做搜索的代碼是從參考指南採取:休眠搜索初學者問題

FullTextEntityManager fullTextEntityManager = 
    Search.getFullTextEntityManager(em); 
EntityTransaction transaction = em.getTransaction(); 

try 
{ 
    transaction.begin(); 

    // create native Lucene query using the query DSL 
    // alternatively you can write the Lucene query using the 
    // Lucene query parser or the Lucene programmatic API. 
    // The Hibernate Search DSL is recommended though 
    SearchFactory sf = fullTextEntityManager.getSearchFactory(); 
    QueryBuilder qb = sf 
     .buildQueryBuilder().forEntity(Item.class).get(); 

    org.apache.lucene.search.Query query = qb 
     .keyword() 
     .onFields("title", "description") 
     .matching(queryString) 
     .createQuery(); 

    // wrap Lucene query in a javax.persistence.Query 
    javax.persistence.Query persistenceQuery = 
    fullTextEntityManager.createFullTextQuery(query, Item.class); 

    // execute search 
    @SuppressWarnings("unchecked") 
    List<Item> result = persistenceQuery.getResultList(); 

    transaction.commit(); 

    return result; 
} 
catch (RuntimeException e) 
{ 
    transaction.rollback(); 
    throw e; 
} 

我注意到查詢詞中析取(OR)解釋條款。我希望他們被解釋爲連詞。

回答

3

如果您使用查詢分析器,那麼你可以這樣來做:

QueryParser queryParser = new QueryParser("all", new GermanSnowBallAnalyzer()); 
    queryParser.setDefaultOperator(QueryParser.AND_OPERATOR); 
    Query luceneQuery = queryParser.parse(QueryParser.escape(keyword)); 
2

既然你正在使用Hibernate搜索查詢DSL,您可以將您的查詢寫爲:

Query luceneQuery = qb 
    .bool() 
     .must(qb.keyword().onField("title").matching(queryString).createQuery()) 
     .must(qb.keyword().onField("description").matching(queryString).createQuery()) 
    .createQuery(); 

請注意,查詢字符串不是通過Lucene查詢分析器進行分析的。它必須包含您要搜索的術語(分析儀將被應用!)