Hibernate Search:获取 SQL IN 运算符的功能

在 Hibernate 搜索中创建查询时,是否可以获得 SQL IN 运算符的功能?


例如,我有这两个简单的类(构造函数、getter 和 setter 被省略):


@Entity

@Indexed

public class Product {

    private long id;

    @Field

    private String title;

    @IndexedEmbedded

    private Category category;

}


@Entity

public class Category {

    private long id;

    @Field

    private String name;

}

目前我有以下查询,按标题搜索产品:


org.apache.lucene.search.Query luceneQuery = queryBuilder

        .keyword()

        .onField("title")

        .matching(queryString)

        .createQuery();

但我只想在特定类别中按标题搜索产品。拥有要搜索的类别 ID(或名称)列表,我该如何创建这样的查询?


我找到了这个 SO question,但作者还没有找到合适的解决方案。也许现在这样的功能已经存在?


如果有任何帮助,我将不胜感激。


偶然的你
浏览 78回答 1
1回答

红糖糍粑

首先,索引类别的id:@Entity@Indexedpublic class Product {&nbsp; &nbsp; private long id;&nbsp; &nbsp; @Field&nbsp; &nbsp; private String title;&nbsp; &nbsp; @IndexedEmbedded&nbsp; &nbsp; private Category category;}@Entitypublic class Category {&nbsp; &nbsp; @Field // Added this&nbsp; &nbsp; private long id;&nbsp; &nbsp; @Field&nbsp; &nbsp; private String name;}然后,确保重新索引您的数据,例如使用质量索引器。然后,如下所述更改您的查询代码。您首先需要“SQL IN”,它在 Lucene 世界中表示为category.id = <first> OR category.id = <second> OR .... 只有布尔运算符与您可能习惯的有所不同(请参见此处);在您的情况下,您希望“至少一个”子句匹配,因此您必须使用should运算符:List<Long> categoryIds = ...; // Provided by the userBooleanJunction<?> categoryIdJunction = queryBuilder.bool();for ( categoryId : categoryIds ) {&nbsp; &nbsp; categoryIdJunction.should(&nbsp; &nbsp; &nbsp; &nbsp; queryBuilder&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .keyword()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .onField("category.id")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .matching(categoryId)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .createQuery();&nbsp; &nbsp; );}org.apache.lucene.search.Query categoryIdQuery = categoryIdJunction.createQuery();最后,您需要将该查询与标题上的其他查询结合起来。为此,使用另一个布尔连接,这次使用must运算符(所有子句必须匹配):org.apache.lucene.search.Query titleQuery = queryBuilder&nbsp; &nbsp; &nbsp; &nbsp; .keyword()&nbsp; &nbsp; &nbsp; &nbsp; .onField("title")&nbsp; &nbsp; &nbsp; &nbsp; .matching(queryString)&nbsp; &nbsp; &nbsp; &nbsp; .createQuery();org.apache.lucene.search.Query luceneQuery = queryBuilder.bool()&nbsp; &nbsp; &nbsp; &nbsp; .must( categoryIdQuery )&nbsp; &nbsp; &nbsp; &nbsp; .must( titleQuery )&nbsp; &nbsp; &nbsp; &nbsp; .createQuery();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java