Search code examples
symfonyelasticsearchfoselasticabundle

What is the best way to manage relations in ElasticSearch?


Sorry if this question have been asked but i couldn't find clear answer on this subject.

I'm having troubles while creating my elasticsearch index, i'm not really sure how to manage relations properly.

Let's say i have we have the following entities:

  • Product
    • id
    • reference
  • Book
    • id
    • name
    • product_id
  • Shirt
    • id
    • color
    • product_id
  • StockItem
    • id
    • supplier_id
    • product_id
    • quantity

I'd like to :

  • Find a shirt from it's color
  • Find all books given by supplier_id 5

I wasn't able to find if i was supposed to do multiple queries, nested objects, parent/children relations, etc... I couldn't find a proper tutorial which says "do it that way".

Actually i'm working with nested objects but i find it quite dirty to redefine, in each of my type, all the data i need.

Do you have some advice on this ?

Thank's.


Solution

  • The key to searching and modeling relationships in Elasticsearch is to denormalize. This is because Lucene has a flat data model with no built-in support for relationships in your data.

    Think of it from the perspective of your search results. What is the thing being searched for? What shows up in your search results? That is the thing you are searching against. If you want to filter or sort those things based on the values in a related object, then you need to pull those values in at indexing time.

    If you're searching for shirts and want to filter by color, then your shirt documents should all have a color field on them. If you are searching books and want to filter to a certain supplier, then you should include the supplier name or ID as a field on your book documents.

    Your choice of language and ES client may make this easier. For example, in Ruby, you can index the results of arbitrary method calls, allowing you to dynamically fetch from other associated models while indexing your data.