QueryBuilder.php 11.5 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
 * @since 2.0
 */
class QueryBuilder extends \yii\base\Object
{
22 23 24 25 26
    /**
     * @var Connection the database connection.
     */
    public $db;

27

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

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

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        if ($query->fields === []) {
            $parts['fields'] = [];
        } elseif ($query->fields !== null) {
            $fields = [];
            $scriptFields = [];
            foreach($query->fields as $key => $field) {
                if (is_int($key)) {
                    $fields[] = $field;
                } else {
                    $scriptFields[$key] = $field;
                }
            }
            if (!empty($fields)) {
                $parts['fields'] = $fields;
            }
            if (!empty($scriptFields)) {
                $parts['script_fields'] = $scriptFields;
            }
        }
        if ($query->source !== null) {
            $parts['_source'] = $query->source;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        }
        if ($query->limit !== null && $query->limit >= 0) {
            $parts['size'] = $query->limit;
        }
        if ($query->offset > 0) {
            $parts['from'] = (int) $query->offset;
        }

        if (empty($query->query)) {
            $parts['query'] = ["match_all" => (object) []];
        } else {
            $parts['query'] = $query->query;
        }

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

101
        if (!empty($query->highlight)) {
102 103
            $parts['highlight'] = $query->highlight;
        }
104 105 106 107 108 109 110 111 112
        if (!empty($query->aggregations)) {
            $parts['aggregations'] = $query->aggregations;
        }
        if (!empty($query->stats)) {
            $parts['stats'] = $query->stats;
        }
        if (!empty($query->suggest)) {
            $parts['suggest'] = $query->suggest;
        }
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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        $sort = $this->buildOrderBy($query->orderBy);
        if (!empty($sort)) {
            $parts['sort'] = $sort;
        }

        $options = [];
        if ($query->timeout !== null) {
            $options['timeout'] = $query->timeout;
        }

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

    /**
     * adds order by condition to the query
     */
    public function buildOrderBy($columns)
    {
        if (empty($columns)) {
            return [];
        }
        $orders = [];
        foreach ($columns as $name => $direction) {
            if (is_string($direction)) {
                $column = $direction;
                $direction = SORT_ASC;
            } else {
                $column = $name;
            }
            if ($column == '_id') {
                $column = '_uid';
            }

            // allow elasticsearch extended syntax as described in http://www.elasticsearch.org/guide/reference/api/search/sort/
            if (is_array($direction)) {
                $orders[] = [$column => $direction];
            } else {
                $orders[] = [$column => ($direction === SORT_DESC ? 'desc' : 'asc')];
            }
        }

        return $orders;
    }

    /**
     * Parses the condition specification and generates the corresponding SQL expression.
165
     *
166
     * @param string|array $condition the condition specification. Please refer to [[Query::where()]] on how to specify a condition.
167 168 169
     * @throws \yii\base\InvalidParamException if unknown operator is used in query
     * @throws \yii\base\NotSupportedException if string conditions are used in where
     * @return string the generated SQL expression
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
     */
    public function buildCondition($condition)
    {
        static $builders = [
            'not' => 'buildNotCondition',
            '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',
        ];

        if (empty($condition)) {
            return [];
        }
        if (!is_array($condition)) {
            throw new NotSupportedException('String conditions in where() are not supported by elasticsearch.');
        }
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
            $operator = strtolower($condition[0]);
            if (isset($builders[$operator])) {
                $method = $builders[$operator];
                array_shift($condition);

                return $this->$method($operator, $condition);
            } else {
                throw new InvalidParamException('Found unknown operator in query: ' . $operator);
            }
        } else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...

            return $this->buildHashCondition($condition);
        }
    }

    private function buildHashCondition($condition)
    {
        $parts = [];
        foreach ($condition as $attribute => $value) {
            if ($attribute == '_id') {
214 215
                if ($value === null) { // there is no null pk
                    $parts[] = ['terms' => ['_uid' => []]]; // this condition is equal to WHERE false
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                } else {
                    $parts[] = ['ids' => ['values' => is_array($value) ? $value : [$value]]];
                }
            } else {
                if (is_array($value)) { // IN condition
                    $parts[] = ['in' => [$attribute => $value]];
                } else {
                    if ($value === null) {
                        $parts[] = ['missing' => ['field' => $attribute, 'existence' => true, 'null_value' => true]];
                    } else {
                        $parts[] = ['term' => [$attribute => $value]];
                    }
                }
            }
        }

        return count($parts) === 1 ? $parts[0] : ['and' => $parts];
    }

235
    private function buildNotCondition($operator, $operands)
236 237 238 239 240 241 242
    {
        if (count($operands) != 1) {
            throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
        }

        $operand = reset($operands);
        if (is_array($operand)) {
243
            $operand = $this->buildCondition($operand);
244 245 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
        }

        return [$operator => $operand];
    }

    private function buildAndCondition($operator, $operands)
    {
        $parts = [];
        foreach ($operands as $operand) {
            if (is_array($operand)) {
                $operand = $this->buildCondition($operand);
            }
            if (!empty($operand)) {
                $parts[] = $operand;
            }
        }
        if (!empty($parts)) {
            return [$operator => $parts];
        } else {
            return [];
        }
    }

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

        list($column, $value1, $value2) = $operands;
        if ($column == '_id') {
            throw new NotSupportedException('Between condition is not supported for the _id field.');
        }
        $filter = ['range' => [$column => ['gte' => $value1, 'lte' => $value2]]];
        if ($operator == 'not between') {
            $filter = ['not' => $filter];
        }

        return $filter;
    }

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

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

        $values = (array) $values;

        if (empty($values) || $column === []) {
296
            return $operator === 'in' ? ['terms' => ['_uid' => []]] : []; // this condition is equal to WHERE false
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        }

        if (count($column) > 1) {
            return $this->buildCompositeInCondition($operator, $column, $values);
        } elseif (is_array($column)) {
            $column = reset($column);
        }
        $canBeNull = false;
        foreach ($values as $i => $value) {
            if (is_array($value)) {
                $values[$i] = $value = isset($value[$column]) ? $value[$column] : null;
            }
            if ($value === null) {
                $canBeNull = true;
                unset($values[$i]);
            }
        }
        if ($column == '_id') {
            if (empty($values) && $canBeNull) { // there is no null pk
316
                $filter = ['terms' => ['_uid' => []]]; // this condition is equal to WHERE false
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
            } else {
                $filter = ['ids' => ['values' => array_values($values)]];
                if ($canBeNull) {
                    $filter = ['or' => [$filter, ['missing' => ['field' => $column, 'existence' => true, 'null_value' => true]]]];
                }
            }
        } 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]]]];
                }
            }
        }
        if ($operator == 'not in') {
            $filter = ['not' => $filter];
        }

        return $filter;
    }

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

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