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 - 将 Spring Boot 1.3.2 升级到 1.4.1 后,Hibernate hbm2ddl (ddl-auto) 失败

java - Hibernate二级缓存以防软删除

elasticsearch - Hibernate-search elasticsearch数据索引是同步的还是异步的

java - 在这种情况下我怎样才能最好地应用Hibernate-Search?

java - Hibernate Search 尝试猜测未索引实体的字段桥

java - 当尝试查找 dll 的位置时,jvm 会查看注册表吗?

java.lang.OutOfMemoryError GCOverhead Limit Exceeded 错误

java - Spring JPA @Query注解,SQL地理定位错误

java - 创建名称为 'application' 的 bean 时出错,未找到默认构造函数;嵌套异常是 java.lang.NoSuchMethodException

java - 如何仅使用一个连接在 hibernate 中执行嵌套事务?