Reputation: 771
I'm using Hibernate Search in version 5.0.0.Final. I have 1 field indexed in 1 table. I'm using a FieldBridge to index that field :
public class CustomBridge implements FieldBridge {
@Override
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
MyFieldType file = (ProductOrderJsonEntity) value;
if (file.getA() != null && file.getB() != null) {
luceneOptions.addFieldToDocument(name + ".ABconcat", file.getA() + file.getB(), document);
}
}
}
I'm using FieldBridge to index a field that does not exist in the DB, so when I try to make query like this, it crashes :
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(MyEntity.class).get();
org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("productOrder.internalReference", "techId").matching(keyword).createQuery();
javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, MyEntity.class);
... with the following error :
org.hibernate.search.exception.SearchException: Unable to find field field.ABconcat in com.something.myapp.MyEntity
Apparently it tries to map the fields I give in the luceneQuery to the Object fields (MyEntity in my case).
Is there any way to query the index on custom fields that does not exist in the database ?
Thanks.
Upvotes: 1
Views: 663
Reputation: 771
I just found out about this post which explains that you can query field that have been indexed through FieldBridge like this :
Query targeting multiple fields
int year = datetime.getYear();
int month = datetime.getMonthOfYear();
int day = datetime.getDayOfMonth();
QueryBuilder qb = sm.buildQueryBuilderForClass(BlogEntry.class).get();
Query q = qb.bool()
.must( qb.keyword().onField("creationdate.year").ignoreFieldBridge().ignoreAnalyzer()
.matching(year).createQuery() )
.must( qb.keyword().onField("creationdate.month").ignoreFieldBridge().ignoreAnalyzer()
.matching(month).createQuery() )
.must( qb.keyword().onField("creationdate.day").ignoreFieldBridge().ignoreAnalyzer()
.matching(day).createQuery() )
.createQuery();
CacheQuery cq = sm.getQuery(q, BlogEntry.class);
System.out.println(cq.getResultSize());
The key is to:
target directly each field,
disable the field bridge conversion for the query,
and it’s probably a good idea to disable the analyzer.
It’s a rather advanced topic and the query DSL will do the right thing most of the time. No need to panic just yet.
But in case you hit a complex type needs, it’s interesting to understand what is going on underneath.
Upvotes: 2