2

我正在使用以下代码使用 hibernate-search 进行搜索。但这标记了搜索查询并执行OR 搜索,而我想做AND 搜索。我怎么做?

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
    String searchQuery = "test query";

    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get();

    TermMatchingContext onFields = qb.keyword().onFields("customer.name","customer.shortDescription","customer.longDescription");

    org.apache.lucene.search.Query query = onFields.matching(searchQuery).createQuery();

    FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class);

    List<Customization> result = persistenceQuery.getResultList();
4

2 回答 2

3
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get();
TermMatchingContext onFields = qb.keyword().onFields("customer.shortDescription",  "customer.longDescription");

BooleanJunction<BooleanJunction> bool = qb.bool();
org.apache.lucene.search.Query query = null;
String[] searchTerms = searchQuery.split("\\s+");
for (int j = 0; j < searchTerms.length; j++) {
   String currentTerm = searchTerms[j];
   bool.must(onFields.matching(currentTerm).createQuery());
}

query = bool.createQuery();

FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class);
resultList = persistenceQuery.getResultList();
于 2012-08-14T18:57:19.850 回答
3

OR逻辑是 Lucene 的默认值。您可以使用此处描述的布尔 DSL 查询 - http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query-querydsl但是,这可能无法解决您的问题但是,因为您似乎将两个查询词都放在一个字符串中。根据您的用例(例如,如果搜索字符串由用户提供),最好从 Lucene 查询解析器获取 Lucene 查询。

于 2012-08-14T09:47:24.620 回答