如何在Hibernate Search中使用布尔运算符 [英] How do I use boolean operators with Hibernate Search

查看:92
本文介绍了如何在Hibernate Search中使用布尔运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Hibernate Search Query DSL ,我不知道如何使用AND或OR等布尔参数构造查询。

I'm learning the Hibernate Search Query DSL, and I'm not sure how to construct queries using boolean arguments such as AND or OR.

例如,假设我想要返回所有具有 firstName 值bill的人员记录或鲍勃。

For example, let's say that I want to return all person records that have a firstName value of "bill" or "bob".

在hibernate文档之后,一个示例使用带有两个子查询的bool()方法,例如:

Following the hibernate docs, one example uses the bool() method w/ two subqueries, such as:

QueryBuilder b = fts.getSearchFactory().buildQueryBuilder().forEntity(Person.class).get();
Query luceneQuery = b.bool()
    .should(b.keyword().onField("firstName").matching("bill").createQuery())
    .should(b.keyword().onField("firstName").matching("bob").createQuery())
    .createQuery();

logger.debug("query 1:{}", luceneQuery.toString());

这最终产生了我想要的lucene查询,但这是使用布尔逻辑的正确方法休眠搜索? should()是否等同于OR(类似地,must()对应于AND)?

This ultimately produces the lucene query that I want, but is this the proper way to use boolean logic with hibernate search? Is "should()" the equivalent of "OR" (similarly, does "must()" correspond to "AND")?.

此外,以这种方式编写查询会让人觉得麻烦。例如,如果我有一个firstNames的集合来匹配怎么办?这种类型的查询首先是DSL的良好匹配吗?

Also, writing a query this way feels cumbersome. For example, what if I had a collection of firstNames to match against? Is this type of query a good match for the DSL in the first place?

推荐答案

是的,你的例子是正确的。布尔运算符被称为而不是 OR ,因为它们在Lucene API和文档中具有名称,并且因为它更合适:它不仅影响布尔值决定,但它也影响结果的得分。

Yes your example is correct. The boolean operators are called should instead of OR because of the names they have in the Lucene API and documentation, and because it is more appropriate: it is not only influencing a boolean decision, but it also affects scoring of the result.

例如,如果您搜索菲亚特品牌或蓝色的汽车,那么品牌菲亚特和蓝色的汽车将也会被退回并且得分高于那些蓝色而不是菲亚特。

For example if you search for cars "of brand Fiat" OR "blue", the cars branded Fiat AND blue will also be returned and having an higher score than those which are blue but not Fiat.

它可能会感觉很麻烦,因为它是程序化的,并提供了许多详细的选项。更简单的替代方法是为查询使用简单字符串,并使用 QueryParser 创建查询。通常,解析器对于解析用户输入很有用,程序化的解析器更容易处理明确定义的字段;例如,如果你有你提到的集合,很容易在 for 循环中构建它。

It might feel cumbersome because it's programmatic and provides many detailed options. A simpler alternative is to use a simple string for your query and use the QueryParser to create the query. Generally the parser is useful to parse user input, the programmatic one is easier to deal with well defined fields; for example if you have the collection you mentioned it's easy to build it in a for loop.

这篇关于如何在Hibernate Search中使用布尔运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆