10. Boolean Query

A query that matches documents matching boolean combinations of other queries. The bool query maps to Lucene BooleanQuery. It is built using one or more boolean clauses, each clause with a typed occurrence.

 1<?php
 2
 3$elastic = new ElasticSearch();
 4
 5// Search using must
 6$search = $elastic->bool()
 7                ->index('my_index')
 8                ->must([
 9                    ['term' => ['name.keyword' => 'Şêro']]
10                ])
11                ->search();
12
13// add filter
14$search = $elastic->bool()
15                ->index('my_index')
16                ->must([
17                    ['term' => ['name.keyword' => 'Şêro']]
18                ])
19                ->filter([
20                        ['term' => ['tags' => 'production']]
21                ])
22                ->minimum_should_match(1)
23                ->boost(1)
24                ->search();
25
26// must not
27                    ...
28                    ->mustNot([
29                        ['range' => ['gte' => 10, 'lte' => 20]]
30                    ]);
31
32// should
33                ...
34                ->should([
35                        ['term' => ['tags' => 'env1']],
36                        ['term' => ['tags' => 'deployed']]
37                    ])
38
39// Merge with SORT
40                    ...
41                    ->mergeWith('elastic.sort', function(){
42                        return $this
43                                ->field('age')
44                                ->order('asc')
45                                ->getMap();
46                    });
47
48// Merge with HIGHLIGHT
49                        ...
50                    ->mergeWith('elastic.highlight', function(){
51                        return $this
52                            ->content('name.keyword', '<div>', '</div>')
53                            ->getMap();
54                    });
55
56// You can add GEO FILTER
57            ...
58            ->addGeoFilter('geo_shape', function(){
59                            return $this
60                                    ->index('location')
61                                    ->type('circle')
62                                    ->text('What is your name')
63                                    ->coordinates([51.30, 20.34])
64                                    ->radius('111km')
65                                    ->getMap();
66            });
67
68return $search;