Terms.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace Elastica\Query;
  3. use Elastica\Exception\InvalidException;
  4. /**
  5. * Terms query.
  6. *
  7. * @author Nicolas Ruflin <spam@ruflin.com>
  8. * @author Roberto Nygaard <roberto@nygaard.es>
  9. *
  10. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
  11. */
  12. class Terms extends AbstractQuery
  13. {
  14. /**
  15. * Terms.
  16. *
  17. * @var array Terms
  18. */
  19. protected $_terms;
  20. /**
  21. * Terms key.
  22. *
  23. * @var string Terms key
  24. */
  25. protected $_key;
  26. /**
  27. * Construct terms query.
  28. *
  29. * @param string $key OPTIONAL Terms key
  30. * @param array $terms OPTIONAL Terms list
  31. */
  32. public function __construct($key = '', array $terms = [])
  33. {
  34. $this->setTerms($key, $terms);
  35. }
  36. /**
  37. * Sets key and terms for the query.
  38. *
  39. * @param string $key Terms key
  40. * @param array $terms terms for the query
  41. *
  42. * @return $this
  43. */
  44. public function setTerms($key, array $terms)
  45. {
  46. $this->_key = $key;
  47. $this->_terms = array_values($terms);
  48. return $this;
  49. }
  50. /**
  51. * Sets key and terms lookup for the query.
  52. *
  53. * @param string $key Terms key
  54. * @param array $termsLookup terms lookup for the query
  55. *
  56. * @return $this
  57. */
  58. public function setTermsLookup($key, array $termsLookup)
  59. {
  60. $this->_key = $key;
  61. $this->_terms = $termsLookup;
  62. return $this;
  63. }
  64. /**
  65. * Adds a single term to the list.
  66. *
  67. * @param string $term Term
  68. *
  69. * @return $this
  70. */
  71. public function addTerm($term)
  72. {
  73. $this->_terms[] = $term;
  74. return $this;
  75. }
  76. /**
  77. * Sets the minimum matching values.
  78. *
  79. * @param int|string $minimum Minimum value
  80. *
  81. * @return $this
  82. */
  83. public function setMinimumMatch($minimum)
  84. {
  85. return $this->setParam('minimum_match', $minimum);
  86. }
  87. /**
  88. * Converts the terms object to an array.
  89. *
  90. * @see \Elastica\Query\AbstractQuery::toArray()
  91. *
  92. * @throws \Elastica\Exception\InvalidException If term key is empty
  93. *
  94. * @return array Query array
  95. */
  96. public function toArray()
  97. {
  98. if (empty($this->_key)) {
  99. throw new InvalidException('Terms key has to be set');
  100. }
  101. $this->setParam($this->_key, $this->_terms);
  102. return parent::toArray();
  103. }
  104. }