【问题标题】:Combining QueryDSL with Hibernate Search and Lucene将 QueryDSL 与 Hibernate Search 和 Lucene 相结合
【发布时间】:2016-06-30 17:20:40
【问题描述】:

我使用 Apache Lucene 配置了 Hibernate Search,以便通过给定坐标更轻松地搜索实体。现在我想知道如何向搜索实体添加更多条件。我也在使用 Spring Data 项目和 Query DSL。我正在尝试使用 QueryDSL 中的 Predicate 类来保持我的应用程序的一致性。有没有可能做到这一点?

My Place.class

@Getter
@Setter
@Entity
@Indexed
@Spatial
public class Place implements Serializable {

    private static final long serialVersionUID = -8379536848917838560L;
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "place_id")
    private Long id;

    //...
    @Longitude
    private Double lng;

    @Latitude
    private Double lat;
    //...
    }

我的仓库类

@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager em;

@Override
@Transactional
public List findAll(Coordinates coordinates, Predicate predicate, Pageable pageable, int maxDistance) {

    FullTextEntityManager fullTextSession = Search.getFullTextEntityManager(em);

    QueryBuilder builder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Place.class).get();

    org.apache.lucene.search.Query luceneQuery = builder
            .spatial()
            .within(maxDistance, Unit.KM)
            .ofCoordinates(coordinates)
            .createQuery();

    FullTextQuery jpaQuery = fullTextSession.createFullTextQuery(luceneQuery, Place.class);
    return jpaQuery.getResultList();
}

【问题讨论】:

    标签: hibernate lucene querydsl hibernate-search


    【解决方案1】:

    我假设您不是在询问将多个全文查询与布尔查询相结合 - 因为我希望文档有足够的示例 - 但您是在询问添加基于 SQL 的限制。

    实际上,可以通过应用Criteria 来进一步限制FullTextQuery,但是虽然这似乎可行,但此功能并非有意为之(背后的有趣故事!),测试不佳且效率不高全部:尽可能避免。它没有被删除,因为有些人真的很喜欢它。

    您可以在示例“5.12。在查询中指定 FetchMode”中找到示例 - 以及有关限制的警告: - http://docs.jboss.org/hibernate/search/5.6/reference/en-US/html_single/

    更好的解决方案是通过仅限制索引字段来运行全文查询,这样查询就可以完全由 Lucene 解析。

    有时它有助于对索引中的其他字段进行编码,以某种方式“预先标记”您想要匹配的 Lucene 文档。这是人们需要有点创意的地方,您可以编写一些自定义的FieldBridgeClassBridge 实现。

    然后您应用Full-Text Filter,或将多个查询与布尔查询组合:请参阅“5.1.2.8. 组合查询”部分。

    【讨论】:

    • 我正在寻找将 lucene 查询与我自己的 sql 查询/条件结合起来的方法,因为我对 sql 而不是 lucene 更有信心,但谢谢。我做了我想做的事,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多