使用特定分析器在Hibernate中执行搜索

时间:2016-11-30 15:55:24

标签: java hibernate jpa lucene hibernate-search

来自http://hibernate.org/search/documentation/getting-started/#indexing

EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
    org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();

// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
    .buildQueryBuilder().forEntity(Book.class).get();
org.apache.lucene.search.Query luceneQuery = qb
  .keyword()
  .onFields("title", "subtitle", "authors.name")
  .matching("Java rocks!")
  .createQuery();

// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query jpaQuery =
    fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);

// execute search
List result = jpaQuery.getResultList();

如何使用与搜索上方的字段或实体不同的特定分析器?

1 个答案:

答案 0 :(得分:2)

您可以按以下方式覆盖用于特定字段或字段的分析器

 QueryBuilder qb = fullTextEntityManager.getSearchFactory()
        .buildQueryBuilder().forEntity(Book.class)
        .overridesForField("title","analyzerName")
        .get();

注意:要覆盖多个字段,您可以再次使用相同的调用,因为overridesForField方法返回一个entityContext本身。

类似这样的事情

QueryBuilder qb = fullTextEntityManager.getSearchFactory()
            .buildQueryBuilder().forEntity(Book.class)
            .overridesForField("title","analyzerName")
            .overridesForField("subtitle","analyzerName2")
            .get();

这是[文档](https://docs.jboss.org/hibernate/search/4.0/api/org/hibernate/search/query/dsl/EntityContext.html#overridesForField(java.lang.String,java.lang.String))。