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

namespace yii\elasticsearch;

use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
12
use yii\db\BaseActiveRecord;
13 14
use yii\helpers\Inflector;
use yii\helpers\Json;
15
use yii\helpers\StringHelper;
16 17 18 19

/**
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
 *
Carsten Brandt committed
20 21 22 23 24 25
 * This class implements the ActiveRecord pattern for the fulltext search and data storage
 * [elasticsearch](http://www.elasticsearch.org/).
 *
 * For defining a record a subclass should at least implement the [[attributes()]] method to define
 * attributes.
 * The primary key (the `_id` field in elasticsearch terms) is represented by `getId()` and `setId()`.
26
 * The primary key is not part of the attributes.
Carsten Brandt committed
27 28 29 30 31 32 33 34 35 36 37 38
 *
 * The following is an example model called `Customer`:
 *
 * ```php
 * class Customer extends \yii\elasticsearch\ActiveRecord
 * {
 *     public function attributes()
 *     {
 *         return ['id', 'name', 'address', 'registration_date'];
 *     }
 * }
 * ```
39
 *
Carsten Brandt committed
40
 * You may override [[index()]] and [[type()]] to define the index and type this record represents.
41 42 43 44
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
45
class ActiveRecord extends BaseActiveRecord
46
{
47 48
	const PRIMARY_KEY_NAME = 'id';

49 50 51
	private $_id;
	private $_version;

52 53 54 55 56 57 58 59
	/**
	 * Returns the database connection used by this AR class.
	 * By default, the "elasticsearch" application component is used as the database connection.
	 * You may override this method if you want to use a different database connection.
	 * @return Connection the database connection used by this AR class.
	 */
	public static function getDb()
	{
60
		return \Yii::$app->getComponent('elasticsearch');
61 62 63
	}

	/**
Qiang Xue committed
64
	 * @inheritdoc
65 66 67 68 69
	 */
	public static function find($q = null)
	{
		$query = static::createQuery();
		if (is_array($q)) {
70
			if (count($q) == 1 && (array_key_exists(ActiveRecord::PRIMARY_KEY_NAME, $q)) && $query->where === null) {
71 72 73 74 75 76
				$pk = $q[ActiveRecord::PRIMARY_KEY_NAME];
				if (is_array($pk)) {
					return  static::mget($pk);
				} else {
					return static::get($pk);
				}
77
			}
78
			return $query->andWhere($q)->one();
79 80 81 82 83 84
		} elseif ($q !== null) {
			return static::get($q);
		}
		return $query;
	}

85 86 87 88 89 90 91 92 93 94
	/**
	 * Gets a record by its primary key.
	 *
	 * @param mixed $primaryKey the primaryKey value
	 * @param array $options options given in this parameter are passed to elasticsearch
	 * as request URI parameters.
	 * Please refer to the [elasticsearch documentation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-get.html)
	 * for more details on these options.
	 * @return static|null The record instance or null if it was not found.
	 */
95 96
	public static function get($primaryKey, $options = [])
	{
97 98 99
		if ($primaryKey === null) {
			return null;
		}
100 101 102 103 104 105 106 107
		$command = static::getDb()->createCommand();
		$result = $command->get(static::index(), static::type(), $primaryKey, $options);
		if ($result['exists']) {
			return static::create($result);
		}
		return null;
	}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	/**
	 * Gets a list of records by its primary keys.
	 *
	 * @param array $primaryKeys an array of primaryKey values
	 * @param array $options options given in this parameter are passed to elasticsearch
	 * as request URI parameters.
	 *
	 * Please refer to the [elasticsearch documentation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-get.html)
	 * for more details on these options.
	 * @return static|null The record instance or null if it was not found.
	 */

	public static function mget($primaryKeys, $options = [])
	{
		if (empty($primaryKeys)) {
			return [];
		}
		$command = static::getDb()->createCommand();
		$result = $command->mget(static::index(), static::type(), $primaryKeys, $options);
		$models = [];
		foreach($result['docs'] as $doc) {
			if ($doc['exists']) {
				$models[] = static::create($doc);
			}
		}
		return $models;
	}

136 137 138 139
	// TODO add more like this feature http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-more-like-this.html

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

140
	/**
Qiang Xue committed
141
	 * @inheritdoc
142
	 */
143
	public static function createQuery()
144
	{
145
		return new ActiveQuery(['modelClass' => get_called_class()]);
146 147
	}

148
	/**
Qiang Xue committed
149
	 * @inheritdoc
150 151 152 153 154 155 156
	 */
	public static function createActiveRelation($config = [])
	{
		return new ActiveRelation($config);
	}

	// TODO implement copy and move as pk change is not possible
157

158 159 160 161 162
	public function getId()
	{
		return $this->_id;
	}

163
	/**
164 165 166 167
	 * Sets the primary key
	 * @param mixed $value
	 * @throws \yii\base\InvalidCallException when record is not new
	 */
168
	public function setId($value)
169 170 171 172 173 174 175 176 177
	{
		if ($this->isNewRecord) {
			$this->_id = $value;
		} else {
			throw new InvalidCallException('Changing the primaryKey of an already saved record is not allowed.');
		}
	}

	/**
Qiang Xue committed
178
	 * @inheritdoc
179 180 181 182
	 */
	public function getPrimaryKey($asArray = false)
	{
		if ($asArray) {
183
			return [ActiveRecord::PRIMARY_KEY_NAME => $this->_id];
184 185 186 187 188 189
		} else {
			return $this->_id;
		}
	}

	/**
Qiang Xue committed
190
	 * @inheritdoc
191 192 193
	 */
	public function getOldPrimaryKey($asArray = false)
	{
194 195
		$id = $this->isNewRecord ? null : $this->_id;
		if ($asArray) {
196
			return [ActiveRecord::PRIMARY_KEY_NAME => $id];
197 198 199
		} else {
			return $this->_id;
		}
200 201 202 203 204 205 206 207 208 209 210
	}

	/**
	 * This method defines the primary.
	 *
	 * The primaryKey for elasticsearch documents is always `primaryKey`. It can not be changed.
	 *
	 * @return string[] the primary keys of this record.
	 */
	public static function primaryKey()
	{
211
		return [ActiveRecord::PRIMARY_KEY_NAME];
212 213 214 215 216 217 218
	}

	/**
	 * Returns the list of all attribute names of the model.
	 * This method must be overridden by child classes to define available attributes.
	 * @return array list of attribute names.
	 */
219
	public function attributes()
220 221 222 223
	{
		throw new InvalidConfigException('The attributes() method of elasticsearch ActiveRecord has to be implemented by child classes.');
	}

224 225 226
	/**
	 * @return string the name of the index this record is stored in.
	 */
227 228
	public static function index()
	{
229
		return Inflector::pluralize(Inflector::camel2id(StringHelper::basename(get_called_class()), '-'));
230 231
	}

232 233 234
	/**
	 * @return string the name of the type of this record.
	 */
235 236
	public static function type()
	{
237
		return Inflector::camel2id(StringHelper::basename(get_called_class()), '-');
238 239 240 241 242 243 244 245 246 247 248
	}

	/**
	 * Creates an active record object using a row of data.
	 * This method is called by [[ActiveQuery]] to populate the query results
	 * into Active Records. It is not meant to be used to create new records.
	 * @param array $row attribute values (name => value)
	 * @return ActiveRecord the newly created active record.
	 */
	public static function create($row)
	{
249
		$row['_source'][ActiveRecord::PRIMARY_KEY_NAME] = $row['_id'];
250 251 252 253 254
		$record = parent::create($row['_source']);
		return $record;
	}

	/**
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
	 * Inserts a document into the associated index using the attribute values of this record.
	 *
	 * This method performs the following steps in order:
	 *
	 * 1. call [[beforeValidate()]] when `$runValidation` is true. If validation
	 *    fails, it will skip the rest of the steps;
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
	 *    rest of the steps;
	 * 4. insert the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
	 *
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
	 *
	 * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
	 *
	 * If the [[primaryKey|primary key]] is not set (null) during insertion,
	 * it will be populated with a
	 * [randomly generated value](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html#_automatic_id_generation)
	 * after insertion.
	 *
	 * For example, to insert a customer record:
	 *
	 * ~~~
	 * $customer = new Customer;
	 * $customer->name = $name;
	 * $customer->email = $email;
	 * $customer->insert();
	 * ~~~
	 *
	 * @param boolean $runValidation whether to perform validation before saving the record.
	 * If the validation fails, the record will not be inserted into the database.
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
	 * meaning all attributes will be saved.
	 * @param array $options options given in this parameter are passed to elasticsearch
	 * as request URI parameters. These are among others:
	 *
	 * - `routing` define shard placement of this record.
	 * - `parent` by giving the primaryKey of another record this defines a parent-child relation
	 * - `timestamp` specifies the timestamp to store along with the document. Default is indexing time.
	 *
	 * Please refer to the [elasticsearch documentation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html)
	 * for more details on these options.
	 *
	 * By default the `op_type` is set to `create`.
	 * @return boolean whether the attributes are valid and the record is inserted successfully.
303
	 */
304
	public function insert($runValidation = true, $attributes = null, $options = ['op_type' => 'create'])
305 306 307 308 309 310 311 312 313 314 315
	{
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		if ($this->beforeSave(true)) {
			$values = $this->getDirtyAttributes($attributes);

			$response = static::getDb()->createCommand()->insert(
				static::index(),
				static::type(),
				$values,
316 317
				$this->getPrimaryKey(),
				$options
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
			);

			if (!$response['ok']) {
				return false;
			}
			$this->_id = $response['_id'];
			$this->_version = $response['_version'];
			$this->setOldAttributes($values);
			$this->afterSave(true);
			return true;
		}
		return false;
	}

	/**
	 * Updates all records whos primary keys are given.
334 335 336
	 * For example, to change the status to be 1 for all customers whose status is 2:
	 *
	 * ~~~
337
	 * Customer::updateAll(array('status' => 1), array(2, 3, 4));
338 339 340 341 342 343 344
	 * ~~~
	 *
	 * @param array $attributes attribute values (name-value pairs) to be saved into the table
	 * @param array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
	 * Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
	 * @return integer the number of rows updated
	 */
345
	public static function updateAll($attributes, $condition = [])
346
	{
347 348
		if (count($condition) == 1 && isset($condition[ActiveRecord::PRIMARY_KEY_NAME])) {
			$primaryKeys = (array) $condition[ActiveRecord::PRIMARY_KEY_NAME];
349
		} else {
350
			$primaryKeys = static::find()->where($condition)->column(ActiveRecord::PRIMARY_KEY_NAME);
351 352
		}
		if (empty($primaryKeys)) {
353 354
			return 0;
		}
355
		$bulk = '';
356
		foreach((array) $primaryKeys as $pk) {
357 358
			$action = Json::encode([
				"update" => [
359
					"_id" => $pk,
360 361 362 363
					"_type" => static::type(),
					"_index" => static::index(),
				],
			]);
364
			$data = Json::encode([
365
				"doc" => $attributes
366
			]);
367
			$bulk .= $action . "\n" . $data . "\n";
368
		}
369 370

		// TODO do this via command
371 372
		$url = [static::index(), static::type(), '_bulk'];
		$response = static::getDb()->post($url, [], $bulk);
373
		$n=0;
374
		foreach($response['items'] as $item) {
375 376
			if ($item['update']['ok']) {
				$n++;
377 378 379 380 381
			}
		}
		return $n;
	}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
	/**
	 * Updates all matching records using the provided counter changes and conditions.
	 * For example, to increment all customers' age by 1,
	 *
	 * ~~~
	 * Customer::updateAllCounters(['age' => 1]);
	 * ~~~
	 *
	 * @param array $counters the counters to be updated (attribute name => increment value).
	 * Use negative values if you want to decrement the counters.
	 * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
	 * Please refer to [[Query::where()]] on how to specify this parameter.
	 * @return integer the number of rows updated
	 */
	public static function updateAllCounters($counters, $condition = [])
	{
		if (count($condition) == 1 && isset($condition[ActiveRecord::PRIMARY_KEY_NAME])) {
			$primaryKeys = (array) $condition[ActiveRecord::PRIMARY_KEY_NAME];
		} else {
			$primaryKeys = static::find()->where($condition)->column(ActiveRecord::PRIMARY_KEY_NAME);
		}
		if (empty($primaryKeys) || empty($counters)) {
			return 0;
		}
		$bulk = '';
		foreach((array) $primaryKeys as $pk) {
			$action = Json::encode([
				"update" => [
					"_id" => $pk,
					"_type" => static::type(),
					"_index" => static::index(),
				],
			]);
			$script = '';
			foreach($counters as $counter => $value) {
				$script .= "ctx._source.$counter += $counter;\n";
			}
			$data = Json::encode([
				"script" => $script,
                "params" => $counters
			]);
			$bulk .= $action . "\n" . $data . "\n";
		}

		// TODO do this via command
		$url = [static::index(), static::type(), '_bulk'];
		$response = static::getDb()->post($url, [], $bulk);

		$n=0;
		foreach($response['items'] as $item) {
			if ($item['update']['ok']) {
				$n++;
			}
		}
		return $n;
	}
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

	/**
	 * Deletes rows in the table using the provided conditions.
	 * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
	 *
	 * For example, to delete all customers whose status is 3:
	 *
	 * ~~~
	 * Customer::deleteAll('status = 3');
	 * ~~~
	 *
	 * @param array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
	 * Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
	 * @return integer the number of rows deleted
	 */
453
	public static function deleteAll($condition = [])
454
	{
455 456
		if (count($condition) == 1 && isset($condition[ActiveRecord::PRIMARY_KEY_NAME])) {
			$primaryKeys = (array) $condition[ActiveRecord::PRIMARY_KEY_NAME];
457
		} else {
458
			$primaryKeys = static::find()->where($condition)->column(ActiveRecord::PRIMARY_KEY_NAME);
459 460
		}
		if (empty($primaryKeys)) {
461 462
			return 0;
		}
463
		$bulk = '';
464
		foreach((array) $primaryKeys as $pk) {
465
			$bulk .= Json::encode([
466
				"delete" => [
467
					"_id" => $pk,
468 469 470 471
					"_type" => static::type(),
					"_index" => static::index(),
				],
			]) . "\n";
472
		}
473 474

		// TODO do this via command
475 476
		$url = [static::index(), static::type(), '_bulk'];
		$response = static::getDb()->post($url, [], $bulk);
477
		$n=0;
478
		foreach($response['items'] as $item) {
479
			if ($item['delete']['found'] && $item['delete']['ok']) {
480 481
				$n++;
			}
482
		}
483
		return $n;
484 485
	}
}