5. Nested

The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.

Using nested fields for arrays of objects

Firstly we need to set mapping to use:

 1<?php
 2
 3$index = $this->elastic
 4                    ->index()
 5                    ->name('my-index')
 6                    ->mappings(function(){
 7                            return $this
 8                                    ->property('user', [
 9                                        'type' => 'nested'
10                                    ])
11                                    ->getMap();
12                    })
13                    ->create();

Save a Nested data:

 1<?php
 2
 3$save = $this->elastic->document()
 4                ->index('my-index')
 5                ->body([
 6                    'group' => 'fans',
 7                    'user' => [
 8                        [
 9                            'first' => 'John',
10                            'last'  => 'Smith'
11                        ],
12                        [
13                            'first' => 'Alice',
14                            'Last' => 'White'
15                        ]
16                    ]
17                ])
18                ->save();

Searhing Nested data:

 1<?php
 2
 3$nested = $this->elastic
 4                    ->nested()
 5                    ->index('my-index')
 6                    ->path('user')
 7                    ->params('size', 2)
 8                    ->addQuery('elastic.bool', function() {
 9                        return $this
10                                ->must([
11                                    [
12                                        'match' => ['user.first' => 'Alice']
13                                    ]
14                                ])
15                                ->getMap();
16                    })
17                    ->search();