QueryBuilder.php 8.15 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 12 13
use yii\base\NotSupportedException;

/**
14
 * QueryBuilder builds an elasticsearch query based on the specification given as a [[Query]] object.
15 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 59 60 61 62 63 64 65 66 67 68 69 70
		$filters = empty($query->filter) ? [] : [$query->filter];
		$whereFilter = $this->buildCondition($query->where);
		if (!empty($whereFilter)) {
			$filters[] = $whereFilter;
		}
		if (!empty($filters)) {
			$parts['filter'] = count($filters) > 1 ? ['and' => $filters] : $filters[0];
		}

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

		if (empty($parts['query'])) {
			$parts['query'] = ["match_all" => (object)[]];
74
		}
75 76 77 78 79 80 81 82 83

		return [
			'queryParts' => $parts,
			'index' => $query->index,
			'type' => $query->type,
			'options' => [
				'timeout' => $query->timeout
			],
		];
84 85 86
	}

	/**
87
	 * adds order by condition to the query
88
	 */
89
	public function buildOrderBy($columns)
90 91
	{
		if (empty($columns)) {
92
			return [];
93
		}
94
		$orders = [];
95 96 97 98 99 100 101
		foreach ($columns as $name => $direction) {
			// allow elasticsearch extended syntax as described in http://www.elasticsearch.org/guide/reference/api/search/sort/
			if (is_array($direction)) {
				$orders[] = array($name => $direction);
			} elseif (is_string($direction)) {
				$orders[] = $direction;
			} else {
102
				$orders[] = array($name => ($direction === SORT_DESC ? 'desc' : 'asc'));
103 104
			}
		}
105
		return $orders;
106 107 108 109 110 111 112 113 114 115
	}

	/**
	 * 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
	 */
116
	public function buildCondition($condition)
117 118
	{
		static $builders = array(
119 120 121 122 123 124 125 126 127 128
			'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',
129 130 131
		);

		if (empty($condition)) {
132
			return [];
133 134
		}
		if (!is_array($condition)) {
135
			throw new NotSupportedException('String conditions in where() are not supported by elasticsearch.');
136 137
		}
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
138
			$operator = strtolower($condition[0]);
139 140 141
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
142
				return $this->$method($operator, $condition);
143
			} else {
144
				throw new InvalidParamException('Found unknown operator in query: ' . $operator);
145 146
			}
		} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
147
			return $this->buildHashCondition($condition);
148 149 150
		}
	}

151
	private function buildHashCondition($condition)
152
	{
153
		$parts = [];
154
		foreach($condition as $attribute => $value) {
155
			if (is_array($value)) { // IN condition
156
				$parts[] = ['in' => [$attribute => $value]];
157 158
			} else {
				if ($value === null) {
159
					$parts[] = ['missing' => ['field' => $attribute, 'existence' => true, 'null_value' => true]];
160
				} else {
161
					$parts[] = ['term' => [$attribute => $value]];
162 163 164
				}
			}
		}
165
		return count($parts) === 1 ? $parts[0] : ['and' => $parts];
166 167
	}

168
	private function buildAndCondition($operator, $operands)
169
	{
170
		$parts = [];
171 172
		foreach ($operands as $operand) {
			if (is_array($operand)) {
173
				$operand = $this->buildCondition($operand);
174
			}
175
			if (!empty($operand)) {
176 177 178 179
				$parts[] = $operand;
			}
		}
		if (!empty($parts)) {
180
			return [$operator => $parts];
181
		} else {
182
			return [];
183 184 185
		}
	}

186
	private function buildBetweenCondition($operator, $operands)
187 188
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
189
			throw new InvalidParamException("Operator '$operator' requires three operands.");
190 191 192
		}

		list($column, $value1, $value2) = $operands;
193 194 195
		$filter = ['range' => [$column => ['gte' => $value1, 'lte' => $value2]]];
		if ($operator == 'not between') {
			$filter = ['not' => $filter];
196
		}
197
		return $filter;
198 199 200 201 202
	}

	private function buildInCondition($operator, $operands, &$params)
	{
		if (!isset($operands[0], $operands[1])) {
203
			throw new InvalidParamException("Operator '$operator' requires two operands.");
204 205 206 207 208 209
		}

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

		$values = (array)$values;

210 211
		if (empty($values) || $column === []) {
			return $operator === 'in' ? ['script' => ['script' => '0=1']] : [];
212 213 214 215 216 217 218
		}

		if (count($column) > 1) {
			return $this->buildCompositeInCondition($operator, $column, $values, $params);
		} elseif (is_array($column)) {
			$column = reset($column);
		}
219
		$canBeNull = false;
220 221
		foreach ($values as $i => $value) {
			if (is_array($value)) {
222
				$values[$i] = $value = isset($value[$column]) ? $value[$column] : null;
223 224
			}
			if ($value === null) {
225 226
				$canBeNull = true;
				unset($values[$i]);
227 228
			}
		}
229 230
		if (empty($values) && $canBeNull) {
			return ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]];
231
		} else {
232 233 234 235 236 237 238 239
			$filter = ['in' => [$column => $values]];
			if ($canBeNull) {
				$filter = ['or' => [$filter, ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]]]];
			}
			if ($operator == 'not in') {
				$filter = ['not' => $filter];
			}
			return $filter;
240 241 242 243 244
		}
	}

	protected function buildCompositeInCondition($operator, $columns, $values, &$params)
	{
245
		throw new NotSupportedException('composite in is not supported by elasticsearch.');
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		$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) . ')';
	}

	private function buildLikeCondition($operator, $operands, &$params)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

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

		$values = (array)$values;

		if (empty($values)) {
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
		}

		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);
	}
}