Reputation: 12039
I have a JPA entity mapped using Hibernate Search. The entity has a field that will consist of an XML String
. Is it possible to index the value of that String
and perform a search against it?
For example, if my XML String
looked like:
<myElement>
<myChildElement>Foo</myChildElement>
</myElement>
Would it be possible to query for Entities with a field that have myChildElement
equal to Foo
? If so, how would I map the field within the entity? How do I form the Hibernate Search query?
Upvotes: 0
Views: 193
Reputation: 9977
I'm not sure it's such a good idea to store XML in entity properties; parsing the XML and storing it as an embeddable object instead of a String field might prove easier in the long run.
But if you have to, yes, you can index that XML-formatted field.
You will have to implement a custom field bridge. In your implementation, you will use some XML parser, extract the values for the XML nodes that matter to you, and add those values to field in the document. Name the fields as you want, xmlField_myElement_myChildElement
as suggested by @Thomas will do just fine.
Then you can map your entity property with @Field(bridge = @FieldBridge(impl = MyFieldBridgeImpl.class))
. You may want to tune other options though, analyzer
in particular.
To query the field, nothing particular, do the usual. You may have to call .ignoreFieldBridge
to avoid your search string being parsed as XML, but that's about it:
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity( MyEntity.class )
.get();
Query luceneQuery = qb.keyword()
.onField("xmlField_myElement_myChildElement")
.ignoreFieldBridge()
.matching(searchString)
.createQuery();
List<MyEntity> results = (List<MyEntity>) fullTextEntityManager
.createFullTextQuery( luceneQuery, MyEntity.class )
.list();
Upvotes: 1