QueryBuilder.php 9.57 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
 *
 *
18
 * @author Carsten Brandt <mail@cebe.cc>
19 20 21 22 23 24 25 26 27 28 29 30 31 32
 * @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
	 */
33
	public function __construct($connection, $config = [])
34 35 36 37 38 39
	{
		$this->db = $connection;
		parent::__construct($config);
	}

	/**
40 41
	 * Generates query from a [[Query]] object.
	 * @param Query $query the [[Query]] object from which the query will be generated
42 43 44 45 46
	 * @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)
	{
47
		$parts = [];
48

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

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

		$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;
78 79 80 81 82 83
		}

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

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

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

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

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

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

	/**
	 * 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
	 */
140
	public function buildCondition($condition)
141 142
	{
		static $builders = array(
143 144 145 146 147 148 149 150 151 152
			'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',
153 154 155
		);

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

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

200
	private function buildAndCondition($operator, $operands)
201
	{
202
		$parts = [];
203 204
		foreach ($operands as $operand) {
			if (is_array($operand)) {
205
				$operand = $this->buildCondition($operand);
206
			}
207
			if (!empty($operand)) {
208 209 210 211
				$parts[] = $operand;
			}
		}
		if (!empty($parts)) {
212
			return [$operator => $parts];
213
		} else {
214
			return [];
215 216 217
		}
	}

218
	private function buildBetweenCondition($operator, $operands)
219 220
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
221
			throw new InvalidParamException("Operator '$operator' requires three operands.");
222 223 224
		}

		list($column, $value1, $value2) = $operands;
225
		if ($column == ActiveRecord::PRIMARY_KEY_NAME) {
226 227
			throw new NotSupportedException('Between condition is not supported for primaryKey.');
		}
228 229 230
		$filter = ['range' => [$column => ['gte' => $value1, 'lte' => $value2]]];
		if ($operator == 'not between') {
			$filter = ['not' => $filter];
231
		}
232
		return $filter;
233 234
	}

235
	private function buildInCondition($operator, $operands)
236 237
	{
		if (!isset($operands[0], $operands[1])) {
238
			throw new InvalidParamException("Operator '$operator' requires two operands.");
239 240 241 242 243 244
		}

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

		$values = (array)$values;

245
		if (empty($values) || $column === []) {
246
			return $operator === 'in' ? ['script' => ['script' => '0==1']] : [];
247 248 249 250 251 252 253
		}

		if (count($column) > 1) {
			return $this->buildCompositeInCondition($operator, $column, $values, $params);
		} elseif (is_array($column)) {
			$column = reset($column);
		}
254
		$canBeNull = false;
255 256
		foreach ($values as $i => $value) {
			if (is_array($value)) {
257
				$values[$i] = $value = isset($value[$column]) ? $value[$column] : null;
258 259
			}
			if ($value === null) {
260 261
				$canBeNull = true;
				unset($values[$i]);
262 263
			}
		}
264
		if ($column == ActiveRecord::PRIMARY_KEY_NAME) {
265 266 267 268 269 270 271
			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]]]];
				}
272
			}
273 274 275 276 277 278 279 280
		} 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]]]];
				}
281
			}
282
		}
283 284 285 286
		if ($operator == 'not in') {
			$filter = ['not' => $filter];
		}
		return $filter;
287 288
	}

289
	protected function buildCompositeInCondition($operator, $columns, $values)
290
	{
291
		throw new NotSupportedException('composite in is not supported by elasticsearch.');
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		$vss = array();
		foreach ($values as $value) {
			$vs = array();
			foreach ($columns as $column) {
				if (isset($value[$column])) {
					$phName = self::PARAM_PREFIX . count($params);
					$params[$phName] = $value[$column];
					$vs[] = $phName;
				} else {
					$vs[] = 'NULL';
				}
			}
			$vss[] = '(' . implode(', ', $vs) . ')';
		}
		foreach ($columns as $i => $column) {
			if (strpos($column, '(') === false) {
				$columns[$i] = $this->db->quoteColumnName($column);
			}
		}
		return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')';
	}

314
	private function buildLikeCondition($operator, $operands)
315
	{
316
		throw new NotSupportedException('like conditions is not supported by elasticsearch.');
317 318 319 320 321 322 323 324 325
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

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

		$values = (array)$values;

		if (empty($values)) {
326
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0==1' : '';
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
		}

		if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
			$andor = ' AND ';
		} else {
			$andor = ' OR ';
			$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
		}

		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}

		$parts = array();
		foreach ($values as $value) {
			$phName = self::PARAM_PREFIX . count($params);
			$params[$phName] = $value;
			$parts[] = "$column $operator $phName";
		}

		return implode($andor, $parts);
	}
}