Elasticsearch 7.6 Multiple Child Relation with Nest

Ali Kizildag
Mar 14, 2020 · 3 min read

I had to use the multiple Join for a project that I was working on in the past days. I looked for the muti join example on the internet but couldn’t find anything even in the official documentation. Finally, I wrote it myself in some way and decided to write this article so that you could use it. Have Fun!

Source Code

You can get the source code form my GitHub.

Intro

If you have experience with any old version of Elasticsearch before 5.6, you probably know the parent-child relation. After version 5.6 Elasticsearch decided to change this relation for some performance reasons (Ref. 5.6 breaking changes). Child documents have been removed. So a new type has entered our world, “Join” type.

According to our scenario, we have four entities such as Product, Category, Supplier, and Stock. Actually we are using the Elasticsearch like a relational database that is not recommended but don’t worry about the usage and project structure(Ref. Removal of Mapping Types). In this article, we just focus on how Join is used.

Project

Basically, the Product is parent and others are its children. So we are going to create a base document class that contains a JoinField. JoinField defines a relationship between parent and child.

Create a Base Document Class

Create Product derives from BaseDocument.

Create Category derives from BaseDocument.

Create other child types like Category.

Create Index and Mapping

We create a mapping manually and describe the relations with the Join extension. The usage is Join<YourParentMappingTypeHere>(“YourChildMappingType1”, “YourChildMappingType2”, “YourChildMappingType3” ….).

If you want to use DSL it should be like this:

Request:

Mapping:

Check mapping with the GET mapping API.

GET multiplejoinindex/_mapping

The response should be like this:

Index Documents

In this step, we are going to index multiple documents with the IndexDocument method. This method will be used for only indexing our Parent document.

Indexing Parent Documents

We are using a different method for indexing child documents. Parent and child documents must be in the same routing. So we have to assign the routing Id (parent Id) when indexing the child documents. That is the difference with the previous method.

Indexing Child Documents

Search

After sending some dummy data to the Elasticsearch index, we are able to search for our parent and child documents.

Use the parent_id query to get the child documents of a parent. (Ref. Parent_Id Query)

Request:

Response:

Use the has_child query to get the parent documents of a child document. (Ref. Has Child Query)

Request:

Response:

Thanks for reading!

Kariyer.net Tech

Kariyer.net