1<?php 2 3namespace Elastica\Query; 4 5use Elastica\Exception\InvalidException; 6 7/** 8 * Terms query. 9 * 10 * @author Nicolas Ruflin <spam@ruflin.com> 11 * @author Roberto Nygaard <roberto@nygaard.es> 12 * 13 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html 14 */ 15class Terms extends AbstractQuery 16{ 17 /** 18 * @var string 19 */ 20 private $field; 21 22 /** 23 * @param list<bool|float|int|string> $terms Terms list, leave empty if building a terms-lookup query 24 */ 25 public function __construct(string $field, array $terms = []) 26 { 27 if ('' === $field) { 28 throw new InvalidException('Terms field name has to be set'); 29 } 30 31 $this->field = $field; 32 $this->setTerms($terms); 33 } 34 35 /** 36 * Sets terms for the query. 37 * 38 * @param list<bool|float|int|string> $terms 39 */ 40 public function setTerms(array $terms): self 41 { 42 return $this->setParam($this->field, $terms); 43 } 44 45 /** 46 * Adds a single term to the list. 47 * 48 * @param bool|float|int|string $term 49 */ 50 public function addTerm($term): self 51 { 52 if (!\is_scalar($term)) { 53 throw new \TypeError(\sprintf('Argument 1 passed to "%s()" must be a scalar, %s given.', __METHOD__, \is_object($term) ? \get_class($term) : \gettype($term))); 54 } 55 56 $terms = $this->getParam($this->field); 57 58 if (isset($terms['index'])) { 59 throw new InvalidException('Mixed terms and terms lookup are not allowed.'); 60 } 61 62 return $this->addParam($this->field, $term); 63 } 64 65 public function setTermsLookup(string $index, string $id, string $path): self 66 { 67 return $this->setParam($this->field, [ 68 'index' => $index, 69 'id' => $id, 70 'path' => $path, 71 ]); 72 } 73 74 public function setBoost(float $boost): self 75 { 76 return $this->setParam('boost', $boost); 77 } 78} 79