QueryBuilder.php 8.56 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\elasticsearch;

10
use yii\base\InvalidParamException;
11
use yii\base\NotSupportedException;
12
use yii\helpers\Json;
13 14

/**
15
 * QueryBuilder builds an elasticsearch query based on the specification given as a [[Query]] object.
16
 *
17
 * @author Carsten Brandt <mail@cebe.cc>
18 19 20 21 22 23 24 25 26 27 28 29 30 31
 * @since 2.0
 */
class QueryBuilder extends \yii\base\Object
{
	/**
	 * @var Connection the database connection.
	 */
	public $db;

	/**
	 * Constructor.
	 * @param Connection $connection the database connection.
	 * @param array $config name-value pairs that will be used to initialize the object properties
	 */
32
	public function __construct($connection, $config = [])
33 34 35 36 37 38
	{
		$this->db = $connection;
		parent::__construct($config);
	}

	/**
39 40
	 * Generates query from a [[Query]] object.
	 * @param Query $query the [[Query]] object from which the query will be generated
41 42 43 44 45
	 * @return array the generated SQL statement (the first array element) and the corresponding
	 * parameters to be bound to the SQL statement (the second array element).
	 */
	public function build($query)
	{
46
		$parts = [];
47

48 49
		if ($query->fields !== null) {
			$parts['fields'] = (array) $query->fields;
50
		}
51 52
		if ($query->limit !== null && $query->limit >= 0) {
			$parts['size'] = $query->limit;
53
		}
54 55 56 57
		if ($query->offset > 0) {
			$parts['from'] = (int) $query->offset;
		}

58
		if (empty($query->query)) {
59
			$parts['query'] = ["match_all" => (object)[]];
60 61
		} else {
			$parts['query'] = $query->query;
62
		}
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

		$whereFilter = $this->buildCondition($query->where);
		if (is_string($query->filter)) {
			if (empty($whereFilter)) {
				$parts['filter'] = $query->filter;
			} else {
				$parts['filter'] = '{"and": [' . $query->filter . ', ' . Json::encode($whereFilter) . ']}';
			}
		} elseif ($query->filter !== null) {
			if (empty($whereFilter)) {
				$parts['filter'] = $query->filter;
			} else {
				$parts['filter'] = ['and' => [$query->filter, $whereFilter]];
			}
		} elseif (!empty($whereFilter)) {
			$parts['filter'] = $whereFilter;
79 80 81 82 83 84
		}

		$sort = $this->buildOrderBy($query->orderBy);
		if (!empty($sort)) {
			$parts['sort'] = $sort;
		}
85

86 87
		if (!empty($query->facets)) {
			$parts['facets'] = $query->facets;
88
		}
89

90 91 92 93 94
		$options = [];
		if ($query->timeout !== null) {
			$options['timeout'] = $query->timeout;
		}

95 96 97 98
		return [
			'queryParts' => $parts,
			'index' => $query->index,
			'type' => $query->type,
99
			'options' => $options,
100
		];
101 102 103
	}

	/**
104
	 * adds order by condition to the query
105
	 */
106
	public function buildOrderBy($columns)
107 108
	{
		if (empty($columns)) {
109
			return [];
110
		}
111
		$orders = [];
112
		foreach ($columns as $name => $direction) {
113 114 115 116 117 118
			if (is_string($direction)) {
				$column = $direction;
				$direction = SORT_ASC;
			} else {
				$column = $name;
			}
119
			if ($column == '_id') {
120
				$column = '_uid';
121 122
			}

123 124
			// allow elasticsearch extended syntax as described in http://www.elasticsearch.org/guide/reference/api/search/sort/
			if (is_array($direction)) {
125
				$orders[] = [$column => $direction];
126
			} else {
127
				$orders[] = [$column => ($direction === SORT_DESC ? 'desc' : 'asc')];
128 129
			}
		}
130
		return $orders;
131 132 133 134 135 136 137 138 139 140
	}

	/**
	 * Parses the condition specification and generates the corresponding SQL expression.
	 * @param string|array $condition the condition specification. Please refer to [[Query::where()]]
	 * on how to specify a condition.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws \yii\db\Exception if the condition is in bad format
	 */
141
	public function buildCondition($condition)
142
	{
Luciano Baraglia committed
143
		static $builders = [
144
			'not' => 'buildNotCondition',
145 146 147 148 149 150 151 152 153 154
			'and' => 'buildAndCondition',
			'or' => 'buildAndCondition',
			'between' => 'buildBetweenCondition',
			'not between' => 'buildBetweenCondition',
			'in' => 'buildInCondition',
			'not in' => 'buildInCondition',
			'like' => 'buildLikeCondition',
			'not like' => 'buildLikeCondition',
			'or like' => 'buildLikeCondition',
			'or not like' => 'buildLikeCondition',
Luciano Baraglia committed
155
		];
156 157

		if (empty($condition)) {
158
			return [];
159 160
		}
		if (!is_array($condition)) {
161
			throw new NotSupportedException('String conditions in where() are not supported by elasticsearch.');
162 163
		}
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
164
			$operator = strtolower($condition[0]);
165 166 167
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
168
				return $this->$method($operator, $condition);
169
			} else {
170
				throw new InvalidParamException('Found unknown operator in query: ' . $operator);
171 172
			}
		} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
173
			return $this->buildHashCondition($condition);
174 175 176
		}
	}

177
	private function buildHashCondition($condition)
178
	{
179
		$parts = [];
AlexGx committed
180
		foreach ($condition as $attribute => $value) {
181
			if ($attribute == '_id') {
182 183 184 185 186
				if ($value == null) { // there is no null pk
					$parts[] = ['script' => ['script' => '0==1']];
				} else {
					$parts[] = ['ids' => ['values' => is_array($value) ? $value : [$value]]];
				}
187
			} else {
188 189
				if (is_array($value)) { // IN condition
					$parts[] = ['in' => [$attribute => $value]];
190
				} else {
191 192 193 194 195
					if ($value === null) {
						$parts[] = ['missing' => ['field' => $attribute, 'existence' => true, 'null_value' => true]];
					} else {
						$parts[] = ['term' => [$attribute => $value]];
					}
196 197 198
				}
			}
		}
199
		return count($parts) === 1 ? $parts[0] : ['and' => $parts];
200 201
	}

202 203 204 205 206 207 208 209 210 211 212 213 214
	private function buildNotCondition($operator, $operands, &$params)
	{
		if (count($operands) != 1) {
			throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
		}

		$operand = reset($operands);
		if (is_array($operand)) {
			$operand = $this->buildCondition($operand, $params);
		}
		return [$operator => $operand];
	}

215
	private function buildAndCondition($operator, $operands)
216
	{
217
		$parts = [];
218 219
		foreach ($operands as $operand) {
			if (is_array($operand)) {
220
				$operand = $this->buildCondition($operand);
221
			}
222
			if (!empty($operand)) {
223 224 225 226
				$parts[] = $operand;
			}
		}
		if (!empty($parts)) {
227
			return [$operator => $parts];
228
		} else {
229
			return [];
230 231 232
		}
	}

233
	private function buildBetweenCondition($operator, $operands)
234 235
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
236
			throw new InvalidParamException("Operator '$operator' requires three operands.");
237 238 239
		}

		list($column, $value1, $value2) = $operands;
240 241
		if ($column == '_id') {
			throw new NotSupportedException('Between condition is not supported for the _id field.');
242
		}
243 244 245
		$filter = ['range' => [$column => ['gte' => $value1, 'lte' => $value2]]];
		if ($operator == 'not between') {
			$filter = ['not' => $filter];
246
		}
247
		return $filter;
248 249
	}

250
	private function buildInCondition($operator, $operands)
251 252
	{
		if (!isset($operands[0], $operands[1])) {
253
			throw new InvalidParamException("Operator '$operator' requires two operands.");
254 255 256 257 258 259
		}

		list($column, $values) = $operands;

		$values = (array)$values;

260
		if (empty($values) || $column === []) {
261
			return $operator === 'in' ? ['script' => ['script' => '0==1']] : [];
262 263 264
		}

		if (count($column) > 1) {
Qiang Xue committed
265
			return $this->buildCompositeInCondition($operator, $column, $values);
266 267 268
		} elseif (is_array($column)) {
			$column = reset($column);
		}
269
		$canBeNull = false;
270 271
		foreach ($values as $i => $value) {
			if (is_array($value)) {
272
				$values[$i] = $value = isset($value[$column]) ? $value[$column] : null;
273 274
			}
			if ($value === null) {
275 276
				$canBeNull = true;
				unset($values[$i]);
277 278
			}
		}
279
		if ($column == '_id') {
280 281 282 283 284 285 286
			if (empty($values) && $canBeNull) { // there is no null pk
				$filter = ['script' => ['script' => '0==1']];
			} else {
				$filter = ['ids' => ['values' => array_values($values)]];
				if ($canBeNull) {
					$filter = ['or' => [$filter, ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]]]];
				}
287
			}
288 289 290 291 292 293 294 295
		} else {
			if (empty($values) && $canBeNull) {
				$filter = ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]];
			} else {
				$filter = ['in' => [$column => array_values($values)]];
				if ($canBeNull) {
					$filter = ['or' => [$filter, ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]]]];
				}
296
			}
297
		}
298 299 300 301
		if ($operator == 'not in') {
			$filter = ['not' => $filter];
		}
		return $filter;
302 303
	}

304
	protected function buildCompositeInCondition($operator, $columns, $values)
305
	{
306
		throw new NotSupportedException('composite in is not supported by elasticsearch.');
307 308
	}

309
	private function buildLikeCondition($operator, $operands)
310
	{
311
		throw new NotSupportedException('like conditions are not supported by elasticsearch.');
312 313
	}
}