user5177570
user5177570

Reputation:

Perform search in Hibernate with specific analyzer

From 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();

How can I use a specific analyzer different then the one used on the fields or entities above search?

Upvotes: 1

Views: 723

Answers (1)

root
root

Reputation: 3957

you can override the analyzer used for the specific field or fields in the following way

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

Note : to override for multiple fields you can use the same call again since the overridesForField method returns an entityContext itself.

something like this

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

Here is [the documentation](https://docs.jboss.org/hibernate/search/4.0/api/org/hibernate/search/query/dsl/EntityContext.html#overridesForField(java.lang.String, java.lang.String)).

Upvotes: 2

Related Questions