QueryBuilder.php 8.24 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 59
		if (empty($parts['query'])) {
			$parts['query'] = ["match_all" => (object)[]];
60
		}
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$values = (array)$values;

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

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

288
	protected function buildCompositeInCondition($operator, $columns, $values)
289
	{
290
		throw new NotSupportedException('composite in is not supported by elasticsearch.');
291 292
	}

293
	private function buildLikeCondition($operator, $operands)
294
	{
295
		throw new NotSupportedException('like conditions is not supported by elasticsearch.');
296 297
	}
}