Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <info@nfq.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ElasticsearchBundle\DSL\Query;
use ONGR\ElasticsearchBundle\DSL\Bool\Bool;
use ONGR\ElasticsearchBundle\DSL\BuilderInterface;
/**
* Provides query container functionality to any class.
*/
trait QueryAwareTrait
{
/**
* @var BuilderInterface[]
*/
private $queries = [];
/**
* @var \ONGR\ElasticsearchBundle\DSL\Bool\Bool
*/
private $boolQuery;
/**
* @param BuilderInterface $query
* @param string $boolType
*
* @return $this
*/
public function addQuery(BuilderInterface $query, $boolType = Bool::MUST)
{
if ($boolType !== Bool::MUST || $this->boolQuery !== null) {
$this->getBoolQuery()->addToBool($query, $boolType);
} else {
$this->queries[$query->getType()] = $query;
}
return $this;
}
/**
* Returns Bool query. Creates new instance if there is not initiated.
*
* @return \ONGR\ElasticsearchBundle\DSL\Bool\Bool
*/
public function getBoolQuery()
{
if (!$this->boolQuery) {
$this->boolQuery = new Bool();
}
return $this->boolQuery;
}
/**
* @param array $params Example values:
* - minimum_should_match => 1
* - boost => 1.
*/
public function setBoolQueryParameters(array $params)
{
$this->getBoolQuery()->setParameters($params);
}
/**
* Checks if there is added specific query.
*
* @param string $type Query type.
*
* @return bool
*/
public function hasQuery($type)
return array_key_exists($type, $this->queries);
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
}
/**
* Removes specific query.
*
* @param string $key
*/
public function removeQuery($key)
{
if ($this->hasQuery($key)) {
unset($this->queries[$key]);
}
}
/**
* Completely resets query.
*/
public function destroyQuery()
{
$this->queries = [];
$this->boolQuery = null;
}
/**
* Return all queries.
*
* @return array
*/
public function getQueries()
{
return $this->queries;
}
/**
* Aggregates all queries to array.
*
* @return array
*/
public function processQueries()
{
if ($this->boolQuery || count($this->getQueries()) > 1) {
$bool = $this->getBoolQuery();
foreach ($this->getQueries() as $query) {
$bool->addToBool($query);
}
return ['query' => [$bool->getType() => $bool->toArray()]];
} elseif (count($this->getQueries()) == 1) {
$query = array_values($this->getQueries())[0];
return ['query' => [$query->getType() => $query->toArray()]];
}
return [];
}
}