如何获取与休眠搜索结果列表相关的对象?

时间:2019-05-21 14:41:43

标签: elasticsearch lucene hibernate-search

我需要搜索一些在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;
}

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

1 个答案:

答案 0 :(得分:1)

您可以只使用sysdate ...,但是如果您确实希望Hibernate Search返回它,则可以使用投影:

select 
    (sysdate - to_char(sysdate-1, 'd') + 1) first_day_of_week --A monday here
from dual