【问题标题】:How to get the object related to hibernate search result list?如何获取与hibernate搜索结果列表相关的对象?
【发布时间】:2019-10-07 23:53:16
【问题描述】:

我需要搜索在 elasticsearch 上编入索引的多个文档。搜索有效,但我需要知道返回搜索的对象类型。

公共列表搜索(字符串术语){

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder authorQB = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Author.class).get();
    QueryBuilder postQB = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Post.class).get();
    QueryBuilder commentQB = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Comment.class).get();

    Query authorLQ = authorQB
            .keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1)
            .onFields(AUTHOR_FIELDS).matching(terms)
            .createQuery();

    Query postLQ = postQB
            .keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1)
            .onFields(POST_FIELDS).matching(terms)
            .createQuery();

    Query commentLQ = commentQB
            .keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1)
            .onFields(COMMENT_FIELDS).matching(terms)
            .createQuery();

    Query luceneQuery = authorQB.bool()
            .should(authorLQ)
            .should(postLQ)
            .should(commentLQ)
            .createQuery();

    javax.persistence.Query jpaQuery = fullTextEntityManager.
            createFullTextQuery(luceneQuery, Author.class, Post.class, Comment.class);

    List<Object> result; // need to know object type

    try {
        result = jpaQuery.getResultList();
    } catch (NoResultException nre) {
        throw new NoResultException("The search for " + terms + " did not get any results");
    }

    return result;
}

这给了我所有对象的列表,但我需要确切知道它是什么类型(作者、帖子或评论)。可以的,谢谢。

【问题讨论】:

    标签: elasticsearch lucene hibernate-search


    【解决方案1】:

    您可以只使用 instanceof... 但如果您真的希望 Hibernate Search 返回它,您可以使用投影:

        FullTextQuery jpaQuery = fullTextEntityManager.
                createFullTextQuery(luceneQuery, Author.class, Post.class, Comment.class);
        jpaQuery.setProjection( ProjectionConstants.OBJECT_CLASS, ProjectionConstants.THIS );
    
        List<Object[]> results = jpaQuery.list();
        for ( Object[] result : results ) {
             Class<?> resultClass = result[0];
             Object resultObject = result[1];
             // ... do stuff ...
        }
    

    【讨论】:

    • 非常感谢,这正是我想要的。
    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 2011-02-21
    • 2017-10-06
    • 2019-09-11
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多