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

namespace yii\elasticsearch;

10
use Yii;
11
use yii\base\Component;
12
use yii\base\NotSupportedException;
13 14
use yii\db\QueryInterface;
use yii\db\QueryTrait;
15

16
/**
Carsten Brandt committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 * Query represents a query to the search API of elasticsearch.
 *
 * Query provides a set of methods to facilitate the specification of different parameters of the query.
 * These methods can be chained together.
 *
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
 * used to perform/execute the DB query against a database.
 *
 * For example,
 *
 * ~~~
 * $query = new Query;
 * $query->fields('id, name')
 *     ->from('myindex', 'users')
 *     ->limit(10);
 * // build and execute the query
 * $command = $query->createCommand();
 * $rows = $command->search(); // this way you get the raw output of elasticsearch.
 * ~~~
 *
 * You would normally call `$query->search()` instead of creating a command as this method
 * adds the `indexBy()` feature and also removes some inconsistencies from the response.
 *
 * Query also provides some methods to easier get some parts of the result only:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
 * - [[count()]]: returns the number of records.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
 * - [[column()]]: returns the value of the first column in the query result.
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
48
 *
49 50 51
 * NOTE: elasticsearch limits the number of records returned to 10 records by default.
 * If you expect to get more records you should specify limit explicitly.
 *
52 53 54 55
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class Query extends Component implements QueryInterface
56
{
57
	use QueryTrait;
58

59
	/**
Carsten Brandt committed
60 61 62 63 64 65 66 67 68 69 70
	 * @var array the fields being retrieved from the documents. For example, `['id', 'name']`.
	 * If not set, it means retrieving all fields. An empty array will result in no fields being
	 * retrieved. This means that only the primaryKey of a record will be available in the result.
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-fields.html#search-request-fields
	 * @see fields()
	 */
	public $fields;
	/**
	 * @var string|array The index to retrieve data from. This can be a string representing a single index
	 * or a an array of multiple indexes. If this is not set, indexes are being queried.
	 * @see from()
71
	 */
72
	public $index;
Carsten Brandt committed
73 74 75 76 77
	/**
	 * @var string|array The type to retrieve data from. This can be a string representing a single type
	 * or a an array of multiple types. If this is not set, all types are being queried.
	 * @see from()
	 */
78
	public $type;
Carsten Brandt committed
79 80 81 82 83 84 85
	/**
	 * @var integer A search timeout, bounding the search request to be executed within the specified time value
	 * and bail with the hits accumulated up to that point when expired. Defaults to no timeout.
	 * @see timeout()
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_3
	 */
	public $timeout;
86 87 88 89
	/**
	 * @var array|string The query part of this search query. This is an array or json string that follows the format of
	 * the elasticsearch [Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html).
	 */
90
	public $query;
91 92 93 94
	/**
	 * @var array|string The filter part of this search query. This is an array or json string that follows the format of
	 * the elasticsearch [Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html).
	 */
95 96 97 98
	public $filter;

	public $facets = [];

99 100 101 102 103 104 105 106 107
	public function init()
	{
		parent::init();
		// setting the default limit according to elasticsearch defaults
		// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_3
		if ($this->limit === null) {
			$this->limit = 10;
		}
	}
108

109 110
	/**
	 * Creates a DB command that can be used to execute this query.
Carsten Brandt committed
111
	 * @param Connection $db the database connection used to execute the query.
112
	 * If this parameter is not given, the `elasticsearch` application component will be used.
113 114 115 116 117
	 * @return Command the created DB command instance.
	 */
	public function createCommand($db = null)
	{
		if ($db === null) {
118
			$db = Yii::$app->getComponent('elasticsearch');
119 120
		}

121 122
		$commandConfig = $db->getQueryBuilder()->build($this);
		return $db->createCommand($commandConfig);
123 124 125 126
	}

	/**
	 * Executes the query and returns all results as an array.
Carsten Brandt committed
127 128
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
129 130 131 132
	 * @return array the query results. If the query results in nothing, an empty array will be returned.
	 */
	public function all($db = null)
	{
133
		$result = $this->createCommand($db)->search();
134 135 136 137
		if (empty($result['hits']['hits'])) {
			return [];
		}
		$rows = $result['hits']['hits'];
Carsten Brandt committed
138
		if ($this->indexBy === null && $this->fields === null) {
139 140
			return $rows;
		}
141
		$models = [];
Carsten Brandt committed
142 143 144 145 146 147 148 149 150 151 152
		foreach ($rows as $key => $row) {
			if ($this->fields !== null) {
				$row['_source'] = isset($row['fields']) ? $row['fields'] : [];
				unset($row['fields']);
			}
			if ($this->indexBy !== null) {
				if (is_string($this->indexBy)) {
					$key = $row['_source'][$this->indexBy];
				} else {
					$key = call_user_func($this->indexBy, $row);
				}
153
			}
154
			$models[$key] = $row;
155
		}
156
		return $models;
157 158 159 160
	}

	/**
	 * Executes the query and returns a single row of result.
Carsten Brandt committed
161 162
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
163 164 165 166 167
	 * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
	 * results in nothing.
	 */
	public function one($db = null)
	{
Carsten Brandt committed
168
		$options['size'] = 1;
169
		$result = $this->createCommand($db)->search($options);
170
		if (empty($result['hits']['hits'])) {
Carsten Brandt committed
171 172
			return false;
		}
173
		$record = reset($result['hits']['hits']);
Carsten Brandt committed
174 175 176 177 178
		if ($this->fields !== null) {
			$record['_source'] = isset($record['fields']) ? $record['fields'] : [];
			unset($record['fields']);
		}
		return $record;
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 214 215 216 217
	/**
	 * Executes the query and returns the complete search result including e.g. hits, facets, totalCount.
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
	 * @param array $options The options given with this query. Possible options are:
	 * - [routing](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search.html#search-routing)
	 * - [search_type](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html)
	 * @return array the query results.
	 */
	public function search($db = null, $options = [])
	{
		$result = $this->createCommand($db)->search($options);
		if (!empty($result['hits']['hits']) && ($this->indexBy === null || $this->fields === null)) {
			$rows = [];
			foreach ($result['hits']['hits'] as $key => $row) {
				if ($this->fields !== null) {
					$row['_source'] = isset($row['fields']) ? $row['fields'] : [];
					unset($row['fields']);
				}
				if ($this->indexBy !== null) {
					if (is_string($this->indexBy)) {
						$key = $row['_source'][$this->indexBy];
					} else {
						$key = call_user_func($this->indexBy, $row);
					}
				}
				$rows[$key] = $row;
			}
			$result['hits']['hits'] = $rows;
		}
		return $result;
	}

	// TODO add query stats http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search.html#stats-groups

	// TODO add scroll/scan http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html#scan

218 219 220 221 222 223 224 225 226 227 228
	/**
	 * Executes the query and deletes all matching documents.
	 *
	 * This will not run facet queries.
	 *
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
	 * @return array the query results. If the query results in nothing, an empty array will be returned.
	 */
	public function delete($db = null)
	{
229 230
		// TODO implement http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html
		throw new NotSupportedException('Delete by query is not implemented yet.');
231 232
	}

233 234
	/**
	 * Returns the query result as a scalar value.
Carsten Brandt committed
235 236
	 * The value returned will be the specified field in the first document of the query results.
	 * @param string $field name of the attribute to select
237
	 * @param Connection $db the database connection used to execute the query.
Carsten Brandt committed
238
	 * If this parameter is not given, the `elasticsearch` application component will be used.
239
	 * @return string the value of the specified attribute in the first record of the query result.
Carsten Brandt committed
240
	 * Null is returned if the query result is empty or the field does not exist.
241
	 */
Carsten Brandt committed
242
	public function scalar($field, $db = null)
243
	{
244
		$record = self::one($db); // TODO limit fields to the one required
Carsten Brandt committed
245 246
		if ($record !== false && isset($record['_source'][$field])) {
			return $record['_source'][$field];
247
		} else {
248
			return null;
249
		}
250 251 252
	}

	/**
253
	 * Executes the query and returns the first column of the result.
Carsten Brandt committed
254 255 256
	 * @param string $field the field to query over
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
257
	 * @return array the first column of the query result. An empty array is returned if the query results in nothing.
258
	 */
Carsten Brandt committed
259
	public function column($field, $db = null)
260
	{
261 262
		$command = $this->createCommand($db);
		$command->queryParts['fields'] = [$field];
263 264 265
		$result = $command->search();
		if (empty($result['hits']['hits'])) {
			return [];
Carsten Brandt committed
266
		}
267 268 269 270 271
		$column = [];
		foreach ($result['hits']['hits'] as $row) {
			$column[] = isset($row['fields'][$field]) ? $row['fields'][$field] : null;
		}
		return $column;
272 273 274
	}

	/**
275
	 * Returns the number of records.
276
	 * @param string $q the COUNT expression. This parameter is ignored by this implementation.
Carsten Brandt committed
277 278
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
279
	 * @return integer number of records
280
	 */
281
	public function count($q = '*', $db = null)
282
	{
283 284 285 286
		// TODO consider sending to _count api instead of _search for performance
		// only when no facety are registerted.
		// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-count.html

287 288
		$options = [];
		$options['search_type'] = 'count';
289
		return $this->createCommand($db)->search($options)['hits']['total'];
290 291 292
	}

	/**
293
	 * Returns a value indicating whether the query result contains any row of data.
Carsten Brandt committed
294 295
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `elasticsearch` application component will be used.
296
	 * @return boolean whether the query result contains any row of data.
297
	 */
298
	public function exists($db = null)
299
	{
300
		return self::one($db) !== false;
301 302 303
	}

	/**
304 305 306 307
	 * Adds a facet search to this query.
	 * @param string $name the name of this facet
	 * @param string $type the facet type. e.g. `terms`, `range`, `histogram`...
	 * @param string|array $options the configuration options for this facet. Can be an array or a json string.
308
	 * @return static the query object itself
309
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-query-facet.html
310
	 */
311
	public function addFacet($name, $type, $options)
312
	{
313 314
		$this->facets[$name] = [$type => $options];
		return $this;
315 316 317
	}

	/**
318 319 320
	 * The `terms facet` allow to specify field facets that return the N most frequent terms.
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
321
	 * @return static the query object itself
322
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-terms-facet.html
323
	 */
324
	public function addTermFacet($name, $options)
325
	{
326
		return $this->addFacet($name, 'terms', $options);
327 328 329
	}

	/**
330 331 332 333
	 * Range facet allows to specify a set of ranges and get both the number of docs (count) that fall
	 * within each range, and aggregated data either based on the field, or using another field.
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
334
	 * @return static the query object itself
335
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-range-facet.html
336
	 */
337
	public function addRangeFacet($name, $options)
338
	{
339
		return $this->addFacet($name, 'range', $options);
340 341 342
	}

	/**
343 344 345 346 347
	 * The histogram facet works with numeric data by building a histogram across intervals of the field values.
	 * Each value is "rounded" into an interval (or placed in a bucket), and statistics are provided per
	 * interval/bucket (count and total).
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
348
	 * @return static the query object itself
349
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-histogram-facet.html
350
	 */
351
	public function addHistogramFacet($name, $options)
352
	{
353
		return $this->addFacet($name, 'histogram', $options);
354 355 356
	}

	/**
357 358 359
	 * A specific histogram facet that can work with date field types enhancing it over the regular histogram facet.
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
360
	 * @return static the query object itself
361
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-date-histogram-facet.html
362
	 */
363
	public function addDateHistogramFacet($name, $options)
364
	{
365 366 367 368 369 370 371 372
		return $this->addFacet($name, 'date_histogram', $options);
	}

	/**
	 * A filter facet (not to be confused with a facet filter) allows you to return a count of the hits matching the filter.
	 * The filter itself can be expressed using the Query DSL.
	 * @param string $name the name of this facet
	 * @param string $filter the query in Query DSL
373
	 * @return static the query object itself
374 375 376 377 378 379 380 381 382 383 384 385
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-filter-facet.html
	 */
	public function addFilterFacet($name, $filter)
	{
		return $this->addFacet($name, 'filter', $filter);
	}

	/**
	 * A facet query allows to return a count of the hits matching the facet query.
	 * The query itself can be expressed using the Query DSL.
	 * @param string $name the name of this facet
	 * @param string $query the query in Query DSL
386
	 * @return static the query object itself
387 388 389 390 391 392 393 394 395 396 397 398
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-query-facet.html
	 */
	public function addQueryFacet($name, $query)
	{
		return $this->addFacet($name, 'query', $query);
	}

	/**
	 * Statistical facet allows to compute statistical data on a numeric fields. The statistical data include count,
	 * total, sum of squares, mean (average), minimum, maximum, variance, and standard deviation.
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
399
	 * @return static the query object itself
400 401 402 403 404 405 406 407 408 409 410 411
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-statistical-facet.html
	 */
	public function addStatisticalFacet($name, $options)
	{
		return $this->addFacet($name, 'statistical', $options);
	}

	/**
	 * The `terms_stats` facet combines both the terms and statistical allowing to compute stats computed on a field,
	 * per term value driven by another field.
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
412
	 * @return static the query object itself
413 414 415 416 417 418 419 420 421 422 423 424
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-terms-stats-facet.html
	 */
	public function addTermsStatsFacet($name, $options)
	{
		return $this->addFacet($name, 'terms_stats', $options);
	}

	/**
	 * The `geo_distance` facet is a facet providing information for ranges of distances from a provided `geo_point`
	 * including count of the number of hits that fall within each range, and aggregation information (like `total`).
	 * @param string $name the name of this facet
	 * @param array $options additional option. Please refer to the elasticsearch documentation for details.
425
	 * @return static the query object itself
426 427 428 429 430 431 432 433 434 435 436 437 438
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-geo-distance-facet.html
	 */
	public function addGeoDistanceFacet($name, $options)
	{
		return $this->addFacet($name, 'geo_distance', $options);
	}

	// TODO add suggesters http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html

	// TODO add validate query http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-validate.html

	// TODO support multi query via static method http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-multi-search.html

439 440 441
	/**
	 * Sets the querypart of this search query.
	 * @param string $query
442
	 * @return static the query object itself
443 444
	 */
	public function query($query)
445
	{
446 447 448
		$this->query = $query;
		return $this;
	}
449

450 451 452
	/**
	 * Sets the filter part of this search query.
	 * @param string $filter
453
	 * @return static the query object itself
454 455 456 457 458
	 */
	public function filter($filter)
	{
		$this->filter = $filter;
		return $this;
459 460
	}

Carsten Brandt committed
461 462 463 464 465 466
	/**
	 * Sets the index and type to retrieve documents from.
	 * @param string|array $index The index to retrieve data from. This can be a string representing a single index
	 * or a an array of multiple indexes. If this is `null` it means that all indexes are being queried.
	 * @param string|array $type The type to retrieve data from. This can be a string representing a single type
	 * or a an array of multiple types. If this is `null` it means that all types are being queried.
467
	 * @return static the query object itself
Carsten Brandt committed
468 469
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-search.html#search-multi-index-type
	 */
470
	public function from($index, $type = null)
471
	{
472 473
		$this->index = $index;
		$this->type = $type;
474
		return $this;
475
	}
Carsten Brandt committed
476 477 478 479 480 481 482 483 484

	/**
	 * Sets the fields to retrieve from the documents.
	 * @param array $fields the fields to be selected.
	 * @return static the query object itself
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-fields.html
	 */
	public function fields($fields)
	{
485
		if (is_array($fields) || $fields === null) {
486 487 488 489
			$this->fields = $fields;
		} else {
			$this->fields = func_get_args();
		}
Carsten Brandt committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
		return $this;
	}

	/**
	 * Sets the search timeout.
	 * @param integer $timeout A search timeout, bounding the search request to be executed within the specified time value
	 * and bail with the hits accumulated up to that point when expired. Defaults to no timeout.
	 * @return static the query object itself
	 * @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_3
	 */
	public function timeout($timeout)
	{
		$this->timeout = $timeout;
		return $this;
	}
505
}