0

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?

1
  • Well, of course you can do that. You might need some custom code though. In the end it's more a matter of how to index and query (arbitrary?) XML in Lucene. I haven't used both (HSEARCH and Lucene) in a while but one way to index that might be to create a Lucene field name from the xpath (e.g. xmlField_myElement_myChildElement) and store the value Foo for that field. Commented Oct 5, 2017 at 15:47

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.