Hibernate搜索结果排序

时间:2014-08-28 07:12:54

标签: java hibernate hibernate-criteria hibernate-search

我正在使用Hibernate Search在我的数据库表中的字段上应用全文搜索。 我这样使用它:

FullTextSession fts=Search.createFullTextSession(session);
QueryBuilder qb2 = fts.getSearchFactory().buildQueryBuilder()
                   .forEntity(DocumentVersion.class).get();
org.apache.lucene.search.Query searchQuery2 = qb2.keyword()
                                              .onField("content")
                                              .matching(search)
                                              .createQuery();

FullTextQuery fullTextQuery2 = fts.createFullTextQuery(searchQuery2,DocumentVersion.class);
fullTextQuery2.setMaxResults(100);
List res=fullTextQuery2 .list();

最后一行是给我根据查询的相关性排列的DocumentVersion对象。 但是,当我使用条件只获取DocumentVersion 前100个最相关的documentId字段时,它始终返回按升序排列的documentId,表明它不是照顾相关性或排名

这个代码是:

FullTextSession fts=Search.createFullTextSession(session);
QueryBuilder qb2 =fts.getSearchFactory().buildQueryBuilder().forEntity(DocumentVersion.class).get();
    org.apache.lucene.search.Query searchQuery2 = qb2.keyword()
            .onField("content")
            .matching(search)
            .createQuery();

FullTextQuery fullTextQuery2 = fts.createFullTextQuery(searchQuery2, DocumentVersion.class);
org.hibernate.Criteria crquery = session.createCriteria(DocumentVersion.class);
crquery.setProjection(Projections.property("documentId"));
crquery.setMaxResults(100);
fullTextQuery2.setCriteriaQuery(crquery);
List res=crquery.list();

我已经搜索了很多内容,以便找到一种方法来选择前100个最相关或排名最高的documentIds,如上所述,但无法找到方法。有人请帮帮我! DocumentVersion类是这样的:

@Entity
@Indexed
@Table(name = "t_document_version")
public class DocumentVersion {

  private long id;
  private long documentId;

  @Field(index=Index.TOKENIZED, store=Store.NO, name="content")
  private String content;
  private Timestamp tstamp;
   ...
}

1 个答案:

答案 0 :(得分:0)

您不能将Hibernate Search查询与Hibernate ORM Criteria查询(org.hibernate.Criteria)混合使用。仅通过ORM Criteria查询支持设置获取样式。如果您想使用Hibernate Search Projection,请查看http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#projections

您必须执行以下操作:

fullTextQuery2.setProjection("documentId");