java - 使用 hibernate-search 在嵌入式实体中实现多个约束

标签 java hibernate hibernate-search

我有一个关于在使用 hibernate-search 执行查询时强制执行多个约束的可能性的问题。

    @Indexed
    public class Contact{
     //ommited fields

    @IndexEmbedded
    private List<Communication> communications;

    //setters - getters

   }

以及相关的类

    @Indexed
    public class Communication{

     @Field(analyze = Analyze.YES, store = Store.YES)
     private String value;

     @Field(analyze = Analyze.YES, store = Store.YES)
     private CommunicationType communicationType;

    @Field(analyze = Analyze.YES, store = Store.YES)
     private CommunicationUsage communicationUsage;

   }

枚举

public static enum CommunicationUsage {
  PRIVATE,
  PROFESSIONNAL
}

public static enum CommunicationType{
  PHONE,
  EMAIL
}

我需要完成的示例查询如下:

查找通信类型为“PHONE”、CommunicationUsage 为“PRIVATE”且 Communication 类的字段值包含字符串 999 的所有联系人

    public List<Contact> search(){

     FullTextEntityManager fullTextEntityManager = 
                    Search.getFullTextEntityManager(em);


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

        org.apache.lucene.search.Query luceneQuery = 
         qb.bool()                    .must(qb.keyword().wildcard().onField("communications.value").matching("*99999*").createQuery())                    .must(qb.keyword().onField("communications.type").ignoreFieldBridge().matching("phone").createQuery())                    .must(qb.keyword().onField("communications.usage").ignoreFieldBridge().matching("private").createQuery())
                .createQuery();


   org.hibernate.search.jpa.FullTextQuery jpaQuery =
      fullTextEntityManager.createFullTextQuery(luceneQuery, Contact.class);

        List result = jpaQuery.getResultList();

}

但是,我收到的联系人的电话号码与所提供的电话号码相匹配,但通信类型和用途不同(例如电话和专业)

那么这种类型的查询是否可以通过hibernate-search来完成?

最佳答案

目前,使用默认索引的 Hibernate 搜索无法解决此用例。问题在于 Hibernate Search 将所有要索引的数据(包括通过 @IndexedEmbedded 注释的关联)扁平化到单个 Lucene Document 中。特别是在这种情况下,人们失去了由单个Communication实例给出的“分组”。如果您有一个 Communication 实例具有您感兴趣的类型,而另一个实例具有您感兴趣的值,则在您的情况下您将获得匹配项。

作为解决方法,您可以为 Communication 实例提供一个自定义类桥,以某种方式连接您感兴趣的值。然后,您将尝试编写一个针对此自定义字段的查询。

关于java - 使用 hibernate-search 在嵌入式实体中实现多个约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34993344/

相关文章:

java - 使用 JPA 和 Spring 时如何更改 java.lang.Enum 的序数?

java - 为什么在 Hibernate 中需要在 session.delete() 之后调用 session.flush()?

java - 使用一个不完全是 JSON 的主体

java - 如何在android中的hashmap中的值的帮助下打印键

java - Libgdx AssetManager 未在恢复时加载资源

java - jpa hibernate复合外键映射

java - Hibernate 搜索排序与排序规则

java - 在 Web 应用程序中启动 Hibernate Search 时出错

lucene - Hibernate Search 自动更新组合字段

java - 无法使用最新的 Firebase 版本创建用户。我得到一个 W/DynamiteModule 和 W/GooglePlayServicesUtil