Search code examples
javajakarta-eesearchsearch-engineelasticsearch

How to store objects which have relations in ElasticSearch (Search engine)


I am going to use ElasticSearch for as the search repository in my application. I have a few questions regarding what is best practice when it comes to organizing objects in the search index when the objects have associations/relations to each other.

From what I know search indexes is a flat structure and doesn't work with the concept of relations in the same way as a database.

Let say you have these domain objects:

Person: - Has a one-to-many relationship with Car

Car: - Is owned by one Person, many-to-one with Person

Department: - Each Department have many People and each Person may belong to many Department, many-to-many

What would be the best way to store this in the search index? What are the options? For instance I want to find all the people belonging to a certain deparment, or all people where the car has more than 300 bhp. I am using the Java client API if it matters.


Solution

  • Elastic search (or Lucene) isn't a relational database, so you would need to flatten your relationship model.

    Try to model a view that gets this structure -

    Car|Person|Department
    

    This will give you all attributes required to lookup a car. This can be imported into a document for Car.

    Similarly

    Person|Department
    

    will give you all information for a person. This will help you lookup a Person

    Department can be a third document.

    You can have multiple documents for each entity. But the relationship needs to be translated as a property of the entity.