Query.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\elasticsearch;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidArgumentException;
  11. use yii\db\QueryInterface;
  12. use yii\db\QueryTrait;
  13. /**
  14. * Query represents a query to the search API of Elasticsearch.
  15. *
  16. * Query provides a set of methods to facilitate the specification of different
  17. * parameters of the query. These methods can be chained together.
  18. *
  19. * By calling [[createCommand()]], we can get a [[Command]] instance which can
  20. * be further used to perform/execute the DB query against a database.
  21. *
  22. * For example,
  23. *
  24. * ~~~
  25. * $query = new Query;
  26. * $query->storedFields('id, name')
  27. * ->from('myindex', 'users')
  28. * ->limit(10);
  29. * // build and execute the query
  30. * $command = $query->createCommand();
  31. * $rows = $command->search(); // this way you get the raw output of Elasticsearch.
  32. * ~~~
  33. *
  34. * You would normally call `$query->search()` instead of creating a command as
  35. * this method adds the `indexBy()` feature and also removes some
  36. * inconsistencies from the response.
  37. *
  38. * Query also provides some methods to easier get some parts of the result only:
  39. *
  40. * - [[one()]]: returns a single record populated with the first row of data.
  41. * - [[all()]]: returns all records based on the query results.
  42. * - [[count()]]: returns the number of records.
  43. * - [[scalar()]]: returns the value of the first column in the first row of the query result.
  44. * - [[column()]]: returns the value of the first column in the query result.
  45. * - [[exists()]]: returns a value indicating whether the query result has data or not.
  46. *
  47. * NOTE: Elasticsearch limits the number of records returned to 10 records by
  48. * default. If you expect to get more records you should specify limit
  49. * explicitly.
  50. *
  51. * @author Carsten Brandt <mail@cebe.cc>
  52. * @since 2.0
  53. */
  54. class Query extends Component implements QueryInterface
  55. {
  56. use QueryTrait;
  57. /**
  58. * @var array the fields being retrieved from the documents. For example,
  59. * `['id', 'name']`. If not set, this option will not be applied to the
  60. * query and no fields will be returned. In this case the `_source` field
  61. * will be returned by default which can be configured using [[source]].
  62. * Setting this to an empty array will result in no fields being retrieved,
  63. * which means that only the primaryKey of a record will be available in
  64. * the result.
  65. * > Note: Field values are [always returned as arrays] even if they only
  66. * > have one value.
  67. *
  68. * [always returned as arrays]: https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html
  69. *
  70. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-stored-fields.html
  71. * @see storedFields()
  72. * @see source
  73. */
  74. public $storedFields;
  75. /**
  76. * @var array the scripted fields being retrieved from the documents.
  77. * Example:
  78. * ```php
  79. * $query->scriptFields = [
  80. * 'value_times_two' => [
  81. * 'script' => "doc['my_field_name'].value * 2",
  82. * ],
  83. * 'value_times_factor' => [
  84. * 'script' => "doc['my_field_name'].value * factor",
  85. * 'params' => [
  86. * 'factor' => 2.0
  87. * ],
  88. * ],
  89. * ]
  90. * ```
  91. *
  92. * > Note: Field values are [always returned as arrays] even if they only have one value.
  93. *
  94. * [always returned as arrays]: https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html
  95. * [script field]: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
  96. *
  97. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
  98. * @see scriptFields()
  99. * @see source
  100. */
  101. public $scriptFields;
  102. /**
  103. * @var array this option controls how the `_source` field is returned from
  104. * the documents. For example, `['id', 'name']` means that only the `id`
  105. * and `name` field should be returned from `_source`. If not set, it
  106. * means retrieving the full `_source` field unless [[fields]] are
  107. * specified. Setting this option to `false` will disable return of the
  108. * `_source` field, this means that only the primaryKey of a record will be
  109. * available in the result.
  110. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html
  111. * @see source()
  112. * @see fields
  113. */
  114. public $source;
  115. /**
  116. * @var string|array The index to retrieve data from. This can be a string
  117. * representing a single index or a an array of multiple indexes. If this
  118. * is not set, indexes are being queried.
  119. * @see from()
  120. */
  121. public $index;
  122. /**
  123. * @var string|array The type to retrieve data from. This can be a string
  124. * representing a single type or a an array of multiple types. If this is
  125. * not set, all types are being queried.
  126. * @see from()
  127. */
  128. public $type;
  129. /**
  130. * @var integer A search timeout, bounding the search request to be
  131. * executed within the specified time value and bail with the hits
  132. * accumulated up to that point when expired. Defaults to no timeout.
  133. * @see timeout()
  134. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#global-search-timeout
  135. */
  136. public $timeout;
  137. /**
  138. * @var array|string The query part of this search query. This is an array
  139. * or json string that follows the format of the elasticsearch
  140. * [Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html).
  141. */
  142. public $query;
  143. /**
  144. * @var array|string The filter part of this search query. This is an array
  145. * or json string that follows the format of the elasticsearch
  146. * [Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html).
  147. */
  148. public $filter;
  149. /**
  150. * @var string|array The `post_filter` part of the search query for
  151. * differentially filter search results and aggregations.
  152. * @see https://www.elastic.co/guide/en/elasticsearch/guide/current/_post_filter.html
  153. * @since 2.0.5
  154. */
  155. public $postFilter;
  156. /**
  157. * @var array The highlight part of this search query. This is an array that allows to highlight search results
  158. * on one or more fields.
  159. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html
  160. */
  161. public $highlight;
  162. /**
  163. * @var array List of aggregations to add to this query.
  164. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
  165. */
  166. public $aggregations = [];
  167. /**
  168. * @var array the 'stats' part of the query. An array of groups to maintain
  169. * a statistics aggregation for.
  170. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#stats-groups
  171. */
  172. public $stats = [];
  173. /**
  174. * @var array list of suggesters to add to this query.
  175. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
  176. */
  177. public $suggest = [];
  178. /**
  179. * @var array list of collapse to add to this query.
  180. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
  181. * @since 2.1.0
  182. */
  183. public $collapse = [];
  184. /**
  185. * @var float Exclude documents which have a _score less than the minimum
  186. * specified in min_score
  187. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-min-score.html
  188. * @since 2.0.4
  189. */
  190. public $minScore;
  191. /**
  192. * @var array list of options that will passed to commands created by this query.
  193. * @see Command::$options
  194. * @since 2.0.4
  195. */
  196. public $options = [];
  197. /**
  198. * @var bool Enables explanation for each hit on how its score was computed.
  199. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-explain.html
  200. * @since 2.0.5
  201. */
  202. public $explain;
  203. /**
  204. * @inheritdoc
  205. */
  206. public function init()
  207. {
  208. parent::init();
  209. // setting the default limit according to Elasticsearch defaults
  210. // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_5
  211. if ($this->limit === null) {
  212. $this->limit = 10;
  213. }
  214. }
  215. /**
  216. * Creates a DB command that can be used to execute this query.
  217. * @param Connection $db the database connection used to execute the query.
  218. * If this parameter is not given, the `elasticsearch` application
  219. * component will be used.
  220. * @return Command the created DB command instance.
  221. */
  222. public function createCommand($db = null)
  223. {
  224. if ($db === null) {
  225. $db = Yii::$app->get('elasticsearch');
  226. }
  227. $commandConfig = $db->getQueryBuilder()->build($this);
  228. return $db->createCommand($commandConfig);
  229. }
  230. /**
  231. * Executes the query and returns all results as an array.
  232. * @param Connection $db the database connection used to execute the query.
  233. * If this parameter is not given, the `elasticsearch` application component will be used.
  234. * @return array the query results. If the query results in nothing, an empty array will be returned.
  235. */
  236. public function all($db = null)
  237. {
  238. if ($this->emulateExecution) {
  239. return [];
  240. }
  241. $result = $this->createCommand($db)->search();
  242. if ($result === false) {
  243. throw new Exception('Elasticsearch search query failed.');
  244. }
  245. if (empty($result['hits']['hits'])) {
  246. return [];
  247. }
  248. $rows = $result['hits']['hits'];
  249. return $this->populate($rows);
  250. }
  251. /**
  252. * Converts the raw query results into the format as specified by this
  253. * query. This method is internally used to convert the data fetched from
  254. * database into the format as required by this query.
  255. * @param array $rows the raw query result from database
  256. * @return array the converted query result
  257. * @since 2.0.4
  258. */
  259. public function populate($rows)
  260. {
  261. if ($this->indexBy === null) {
  262. return $rows;
  263. }
  264. $models = [];
  265. foreach ($rows as $key => $row) {
  266. if ($this->indexBy !== null) {
  267. if (is_string($this->indexBy)) {
  268. $key = isset($row['fields'][$this->indexBy]) ?
  269. reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
  270. } else {
  271. $key = call_user_func($this->indexBy, $row);
  272. }
  273. }
  274. $models[$key] = $row;
  275. }
  276. return $models;
  277. }
  278. /**
  279. * Executes the query and returns a single row of result.
  280. * @param Connection $db the database connection used to execute the query.
  281. * If this parameter is not given, the `elasticsearch` application
  282. * component will be used.
  283. * @return array|bool the first row (in terms of an array) of the query
  284. * result. False is returned if the query results in nothing.
  285. */
  286. public function one($db = null)
  287. {
  288. if ($this->emulateExecution) {
  289. return false;
  290. }
  291. $result = $this->createCommand($db)->search(['size' => 1]);
  292. if ($result === false) {
  293. throw new Exception('Elasticsearch search query failed.');
  294. }
  295. if (empty($result['hits']['hits'])) {
  296. return false;
  297. }
  298. $record = reset($result['hits']['hits']);
  299. return $record;
  300. }
  301. /**
  302. * Executes the query and returns the complete search result including e.g.
  303. * hits, aggregations, suggesters, totalCount.
  304. * @param Connection $db the database connection used to execute the query.
  305. * If this parameter is not given, the `elasticsearch` application
  306. * component will be used.
  307. * @param array $options The options given with this query. Possible
  308. * options are:
  309. *
  310. * - [routing](https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#search-routing)
  311. *
  312. * @return array the query results.
  313. */
  314. public function search($db = null, $options = [])
  315. {
  316. if ($this->emulateExecution) {
  317. return [
  318. 'hits' => [
  319. 'total' => 0,
  320. 'hits' => [],
  321. ],
  322. ];
  323. }
  324. $result = $this->createCommand($db)->search($options);
  325. if ($result === false) {
  326. throw new Exception('Elasticsearch search query failed.');
  327. }
  328. if (!empty($result['hits']['hits']) && $this->indexBy !== null) {
  329. $rows = [];
  330. foreach ($result['hits']['hits'] as $key => $row) {
  331. if (is_string($this->indexBy)) {
  332. $key = isset($row['fields'][$this->indexBy]) ?
  333. $row['fields'][$this->indexBy] : $row['_source'][$this->indexBy];
  334. } else {
  335. $key = call_user_func($this->indexBy, $row);
  336. }
  337. $rows[$key] = $row;
  338. }
  339. $result['hits']['hits'] = $rows;
  340. }
  341. return $result;
  342. }
  343. /**
  344. * Executes the query and deletes all matching documents.
  345. *
  346. * Everything except query and filter will be ignored.
  347. *
  348. * @param Connection $db the database connection used to execute the query.
  349. * If this parameter is not given, the `elasticsearch` application
  350. * component will be used.
  351. * @param array $options The options given with this query.
  352. * @return array the query results.
  353. */
  354. public function delete($db = null, $options = [])
  355. {
  356. if ($this->emulateExecution) {
  357. return [];
  358. }
  359. return $this->createCommand($db)->deleteByQuery($options);
  360. }
  361. /**
  362. * Returns the query result as a scalar value. The value returned will be
  363. * the specified field in the first document of the query results.
  364. * @param string $field name of the attribute to select
  365. * @param Connection $db the database connection used to execute the query.
  366. * If this parameter is not given, the `elasticsearch` application
  367. * component will be used.
  368. * @return string the value of the specified attribute in the first record
  369. * of the query result. Null is returned if the query result is empty or
  370. * the field does not exist.
  371. */
  372. public function scalar($field, $db = null)
  373. {
  374. if ($this->emulateExecution) {
  375. return null;
  376. }
  377. $record = self::one($db);
  378. if ($record !== false) {
  379. if ($field === '_id') {
  380. return $record['_id'];
  381. } elseif (isset($record['_source'][$field])) {
  382. return $record['_source'][$field];
  383. } elseif (isset($record['fields'][$field])) {
  384. return count($record['fields'][$field]) == 1 ? reset($record['fields'][$field]) : $record['fields'][$field];
  385. }
  386. }
  387. return null;
  388. }
  389. /**
  390. * Executes the query and returns the first column of the result.
  391. * @param string $field the field to query over
  392. * @param Connection $db the database connection used to execute the query.
  393. * If this parameter is not given, the `elasticsearch` application
  394. * component will be used.
  395. * @return array the first column of the query result. An empty array is
  396. * returned if the query results in nothing.
  397. */
  398. public function column($field, $db = null)
  399. {
  400. if ($this->emulateExecution) {
  401. return [];
  402. }
  403. $command = $this->createCommand($db);
  404. $command->queryParts['_source'] = [$field];
  405. $result = $command->search();
  406. if ($result === false) {
  407. throw new Exception('Elasticsearch search query failed.');
  408. }
  409. if (empty($result['hits']['hits'])) {
  410. return [];
  411. }
  412. $column = [];
  413. foreach ($result['hits']['hits'] as $row) {
  414. if (isset($row['fields'][$field])) {
  415. $column[] = $row['fields'][$field];
  416. } elseif (isset($row['_source'][$field])) {
  417. $column[] = $row['_source'][$field];
  418. } else {
  419. $column[] = null;
  420. }
  421. }
  422. return $column;
  423. }
  424. /**
  425. * Returns the number of records.
  426. * @param string $q the COUNT expression. This parameter is ignored by this implementation.
  427. * @param Connection $db the database connection used to execute the query.
  428. * If this parameter is not given, the `elasticsearch` application
  429. * component will be used.
  430. * @return int number of records
  431. */
  432. public function count($q = '*', $db = null)
  433. {
  434. if ($this->emulateExecution) {
  435. return 0;
  436. }
  437. $command = $this->createCommand($db);
  438. // performing a query with return size of 0, is equal to getting result stats such as count
  439. // https://www.elastic.co/guide/en/elasticsearch/reference/5.6/breaking_50_search_changes.html#_literal_search_type_literal
  440. $searchOptions = ['size' => 0];
  441. // Set track_total_hits to 'true' for ElasticSearch version 6 and up
  442. // https://www.elastic.co/guide/en/elasticsearch/reference/master/search-your-data.html#track-total-hits
  443. if ($command->db->dslVersion >= 6) {
  444. $searchOptions['track_total_hits'] = 'true';
  445. }
  446. $result = $command->search($searchOptions);
  447. // since ES7 totals are returned as array (with count and precision values)
  448. if (isset($result['hits']['total'])) {
  449. return is_array($result['hits']['total']) ? (int)$result['hits']['total']['value'] : (int)$result['hits']['total'];
  450. }
  451. return 0;
  452. }
  453. /**
  454. * Returns a value indicating whether the query result contains any row of
  455. * data.
  456. * @param Connection $db the database connection used to execute the query.
  457. * If this parameter is not given, the `elasticsearch` application
  458. * component will be used.
  459. * @return bool whether the query result contains any row of data.
  460. */
  461. public function exists($db = null)
  462. {
  463. return self::one($db) !== false;
  464. }
  465. /**
  466. * Adds a 'stats' part to the query.
  467. * @param array $groups an array of groups to maintain a statistics aggregation for.
  468. * @return $this the query object itself
  469. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#stats-groups
  470. */
  471. public function stats($groups)
  472. {
  473. $this->stats = $groups;
  474. return $this;
  475. }
  476. /**
  477. * Sets a highlight parameters to retrieve from the documents.
  478. * @param array $highlight array of parameters to highlight results.
  479. * @return $this the query object itself
  480. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html
  481. */
  482. public function highlight($highlight)
  483. {
  484. $this->highlight = $highlight;
  485. return $this;
  486. }
  487. /**
  488. * @deprecated since 2.0.5 use addAggragate() instead
  489. *
  490. * Adds an aggregation to this query.
  491. * @param string $name the name of the aggregation
  492. * @param string $type the aggregation type. e.g. `terms`, `range`,
  493. * `histogram`, ...
  494. * @param string|array $options the configuration options for this
  495. * aggregation. Can be an array or a json string.
  496. * @return $this the query object itself
  497. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
  498. */
  499. public function addAggregation($name, $type, $options)
  500. {
  501. return $this->addAggregate($name, [$type => $options]);
  502. }
  503. /**
  504. * @deprecated since 2.0.5 use addAggregate() instead
  505. *
  506. * Adds an aggregation to this query.
  507. *
  508. * This is an alias for [[addAggregation]].
  509. *
  510. * @param string $name the name of the aggregation
  511. * @param string $type the aggregation type. e.g. `terms`, `range`, `histogram`...
  512. * @param string|array $options the configuration options for this
  513. * aggregation. Can be an array or a json string.
  514. * @return $this the query object itself
  515. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
  516. */
  517. public function addAgg($name, $type, $options)
  518. {
  519. return $this->addAggregate($name, [$type => $options]);
  520. }
  521. /**
  522. * Adds an aggregation to this query. Supports nested aggregations.
  523. * @param string $name the name of the aggregation
  524. * @param string|array $options the configuration options for this
  525. * aggregation. Can be an array or a json string.
  526. * @return $this the query object itself
  527. * @see https://www.elastic.co/guide/en/elasticsearch/reference/2.3/search-aggregations.html
  528. */
  529. public function addAggregate($name, $options)
  530. {
  531. $this->aggregations[$name] = $options;
  532. return $this;
  533. }
  534. /**
  535. * Adds a suggester to this query.
  536. * @param string $name the name of the suggester
  537. * @param string|array $definition the configuration options for this
  538. * suggester. Can be an array or a json string.
  539. * @return $this the query object itself
  540. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
  541. */
  542. public function addSuggester($name, $definition)
  543. {
  544. $this->suggest[$name] = $definition;
  545. return $this;
  546. }
  547. /**
  548. * Adds a collapse to this query.
  549. * @param array $collapse the configuration options for collapse.
  550. * @return $this the query object itself
  551. * @see https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-request-collapse.html#search-request-collapse
  552. * @since 2.1.0
  553. */
  554. public function addCollapse($collapse)
  555. {
  556. $this->collapse = $collapse;
  557. return $this;
  558. }
  559. // TODO add validate query https://www.elastic.co/guide/en/elasticsearch/reference/current/search-validate.html
  560. // TODO support multi query via static method https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html
  561. /**
  562. * Sets the query part of this search query.
  563. * @param string|array $query
  564. * @return $this the query object itself
  565. */
  566. public function query($query)
  567. {
  568. $this->query = $query;
  569. return $this;
  570. }
  571. /**
  572. * Starts a batch query.
  573. *
  574. * A batch query supports fetching data in batches, which can keep the
  575. * memory usage under a limit. This method will return a [[BatchQueryResult]]
  576. * object which implements the [[\Iterator]] interface and can be traversed
  577. * to retrieve the data in batches.
  578. *
  579. * For example,
  580. *
  581. * ```php
  582. * $query = (new Query)->from('user');
  583. * foreach ($query->batch() as $rows) {
  584. * // $rows is an array of 10 or fewer rows from user table
  585. * }
  586. * ```
  587. *
  588. * Batch size is determined by the `limit` setting (note that in scan mode
  589. * batch limit is per shard).
  590. *
  591. * @param string $scrollWindow how long Elasticsearch should keep the
  592. * search context alive, in
  593. * [time units](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units)
  594. * @param Connection $db the database connection. If not set, the
  595. * `elasticsearch` application component will be used.
  596. * @return BatchQueryResult the batch query result. It implements the
  597. * [[\Iterator]] interface and can be traversed to retrieve the data in
  598. * batches.
  599. * @since 2.0.4
  600. */
  601. public function batch($scrollWindow = '1m', $db = null)
  602. {
  603. return Yii::createObject([
  604. 'class' => BatchQueryResult::className(),
  605. 'query' => $this,
  606. 'scrollWindow' => $scrollWindow,
  607. 'db' => $db,
  608. 'each' => false,
  609. ]);
  610. }
  611. /**
  612. * Starts a batch query and retrieves data row by row.
  613. *
  614. * This method is similar to [[batch()]] except that in each iteration of
  615. * the result, only one row of data is returned. For example,
  616. *
  617. * ```php
  618. * $query = (new Query)->from('user');
  619. * foreach ($query->each() as $row) {
  620. * }
  621. * ```
  622. *
  623. * @param string $scrollWindow how long Elasticsearch should keep the
  624. * search context alive, in
  625. * [time units](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units)
  626. * @param Connection $db the database connection. If not set, the
  627. * `elasticsearch` application component will be used.
  628. * @return BatchQueryResult the batch query result. It implements the
  629. * [[\Iterator]] interface and can be traversed to retrieve the data in
  630. * batches.
  631. * @since 2.0.4
  632. */
  633. public function each($scrollWindow = '1m', $db = null)
  634. {
  635. return Yii::createObject([
  636. 'class' => BatchQueryResult::className(),
  637. 'query' => $this,
  638. 'scrollWindow' => $scrollWindow,
  639. 'db' => $db,
  640. 'each' => true,
  641. ]);
  642. }
  643. /**
  644. * Sets the index and type to retrieve documents from.
  645. * @param string|array $index The index to retrieve data from. This can be
  646. * a string representing a single index or a an array of multiple indexes.
  647. * If this is `null` it means that all indexes are being queried.
  648. * @param string|array $type The type to retrieve data from. This can be a
  649. * string representing a single type or a an array of multiple types. If
  650. * this is `null` it means that all types are being queried.
  651. * @return $this the query object itself
  652. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html#search-multi-index-type
  653. */
  654. public function from($index, $type = null)
  655. {
  656. $this->index = $index;
  657. $this->type = $type;
  658. return $this;
  659. }
  660. /**
  661. * Sets the fields to retrieve from the documents.
  662. *
  663. * Quote from the Elasticsearch doc:
  664. * > The stored_fields parameter is about fields that are explicitly marked
  665. * > as stored in the mapping, which is off by default and generally not
  666. * > recommended. Use source filtering instead to select subsets of the
  667. * > original source document to be returned.
  668. *
  669. * @param array $fields the fields to be selected.
  670. * @return $this the query object itself
  671. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-stored-fields.html
  672. */
  673. public function storedFields($fields)
  674. {
  675. if (is_array($fields) || $fields === null) {
  676. $this->storedFields = $fields;
  677. } else {
  678. $this->storedFields = func_get_args();
  679. }
  680. return $this;
  681. }
  682. /**
  683. * Sets the script fields to retrieve from the documents.
  684. * @param array $fields the fields to be selected.
  685. * @return $this the query object itself
  686. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
  687. */
  688. public function scriptFields($fields)
  689. {
  690. if (is_array($fields) || $fields === null) {
  691. $this->scriptFields = $fields;
  692. } else {
  693. $this->scriptFields = func_get_args();
  694. }
  695. return $this;
  696. }
  697. /**
  698. * Sets the source filtering, specifying how the `_source` field of the
  699. * document should be returned.
  700. * @param array|string|null|false $source the source patterns to be selected.
  701. * @return $this the query object itself
  702. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html
  703. */
  704. public function source($source)
  705. {
  706. if (is_array($source) || $source === null || $source === false) {
  707. $this->source = $source;
  708. } else {
  709. $this->source = func_get_args();
  710. }
  711. return $this;
  712. }
  713. /**
  714. * Sets the search timeout.
  715. * @param int $timeout A search timeout, bounding the search request to
  716. * be executed within the specified time value and bail with the hits
  717. * accumulated up to that point when expired. Defaults to no timeout.
  718. * @return $this the query object itself
  719. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_5
  720. */
  721. public function timeout($timeout)
  722. {
  723. $this->timeout = $timeout;
  724. return $this;
  725. }
  726. /**
  727. * @param float $minScore Exclude documents which have a `_score` less than
  728. * the minimum specified minScore
  729. * @return $this the query object itself
  730. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-min-score.html
  731. * @since 2.0.4
  732. */
  733. public function minScore($minScore)
  734. {
  735. $this->minScore = $minScore;
  736. return $this;
  737. }
  738. /**
  739. * Sets the options to be passed to the command created by this query.
  740. * @param array $options the options to be set.
  741. * @return $this the query object itself
  742. * @throws InvalidArgumentException if $options is not an array
  743. * @see Command::$options
  744. * @since 2.0.4
  745. */
  746. public function options($options)
  747. {
  748. if (!is_array($options)) {
  749. throw new InvalidArgumentException('Array parameter expected, ' . gettype($options) . ' received.');
  750. }
  751. $this->options = $options;
  752. return $this;
  753. }
  754. /**
  755. * Adds more options, overwriting existing options.
  756. * @param array $options the options to be added.
  757. * @return $this the query object itself
  758. * @throws InvalidArgumentException if $options is not an array
  759. * @see options()
  760. * @since 2.0.4
  761. */
  762. public function addOptions($options)
  763. {
  764. if (!is_array($options)) {
  765. throw new InvalidArgumentException('Array parameter expected, ' . gettype($options) . ' received.');
  766. }
  767. $this->options = array_merge($this->options, $options);
  768. return $this;
  769. }
  770. /**
  771. * @inheritdoc
  772. */
  773. public function andWhere($condition)
  774. {
  775. if ($this->where === null) {
  776. $this->where = $condition;
  777. } else if (isset($this->where[0]) && $this->where[0] === 'and') {
  778. $this->where[] = $condition;
  779. } else {
  780. $this->where = ['and', $this->where, $condition];
  781. }
  782. return $this;
  783. }
  784. /**
  785. * @inheritdoc
  786. */
  787. public function orWhere($condition)
  788. {
  789. if ($this->where === null) {
  790. $this->where = $condition;
  791. } else if (isset($this->where[0]) && $this->where[0] === 'or') {
  792. $this->where[] = $condition;
  793. } else {
  794. $this->where = ['or', $this->where, $condition];
  795. }
  796. return $this;
  797. }
  798. /**
  799. * Set the `post_filter` part of the search query.
  800. * @param string|array $filter
  801. * @return $this the query object itself
  802. * @see $postFilter
  803. * @since 2.0.5
  804. */
  805. public function postFilter($filter)
  806. {
  807. $this->postFilter = $filter;
  808. return $this;
  809. }
  810. /**
  811. * Explain for how the score of each document was computer
  812. * @param $explain
  813. * @return $this
  814. * @see $explain
  815. * @since 2.0.5
  816. */
  817. public function explain($explain)
  818. {
  819. $this->explain = $explain;
  820. return $this;
  821. }
  822. }