vendor/ruflin/elastica/lib/Elastica/Index.php line 133

Open in your IDE?
  1. <?php
  2. namespace Elastica;
  3. use Elastica\Exception\InvalidException;
  4. use Elastica\Exception\ResponseException;
  5. use Elastica\Index\Settings as IndexSettings;
  6. use Elastica\Index\Stats as IndexStats;
  7. use Elastica\ResultSet\BuilderInterface;
  8. use Elasticsearch\Endpoints\AbstractEndpoint;
  9. use Elasticsearch\Endpoints\DeleteByQuery;
  10. use Elasticsearch\Endpoints\Indices\Aliases\Update;
  11. use Elasticsearch\Endpoints\Indices\Analyze;
  12. use Elasticsearch\Endpoints\Indices\Cache\Clear;
  13. use Elasticsearch\Endpoints\Indices\Close;
  14. use Elasticsearch\Endpoints\Indices\Create;
  15. use Elasticsearch\Endpoints\Indices\Delete;
  16. use Elasticsearch\Endpoints\Indices\Exists;
  17. use Elasticsearch\Endpoints\Indices\Flush;
  18. use Elasticsearch\Endpoints\Indices\ForceMerge;
  19. use Elasticsearch\Endpoints\Indices\Mapping\Get;
  20. use Elasticsearch\Endpoints\Indices\Open;
  21. use Elasticsearch\Endpoints\Indices\Refresh;
  22. use Elasticsearch\Endpoints\Indices\Settings\Put;
  23. /**
  24.  * Elastica index object.
  25.  *
  26.  * Handles reads, deletes and configurations of an index
  27.  *
  28.  * @author   Nicolas Ruflin <spam@ruflin.com>
  29.  */
  30. class Index implements SearchableInterface
  31. {
  32.     /**
  33.      * Index name.
  34.      *
  35.      * @var string Index name
  36.      */
  37.     protected $_name;
  38.     /**
  39.      * Client object.
  40.      *
  41.      * @var \Elastica\Client Client object
  42.      */
  43.     protected $_client;
  44.     /**
  45.      * Creates a new index object.
  46.      *
  47.      * All the communication to and from an index goes of this object
  48.      *
  49.      * @param \Elastica\Client $client Client object
  50.      * @param string           $name   Index name
  51.      */
  52.     public function __construct(Client $client$name)
  53.     {
  54.         $this->_client $client;
  55.         if (!is_scalar($name)) {
  56.             throw new InvalidException('Index name should be a scalar type');
  57.         }
  58.         $this->_name = (string) $name;
  59.     }
  60.     /**
  61.      * Returns a type object for the current index with the given name.
  62.      *
  63.      * @param string $type Type name
  64.      *
  65.      * @return \Elastica\Type Type object
  66.      */
  67.     public function getType($type)
  68.     {
  69.         return new Type($this$type);
  70.     }
  71.     /**
  72.      * Return Index Stats.
  73.      *
  74.      * @return \Elastica\Index\Stats
  75.      */
  76.     public function getStats()
  77.     {
  78.         return new IndexStats($this);
  79.     }
  80.     /**
  81.      * Gets all the type mappings for an index.
  82.      *
  83.      * @return array
  84.      */
  85.     public function getMapping()
  86.     {
  87.         $response $this->requestEndpoint(new Get());
  88.         $data $response->getData();
  89.         // Get first entry as if index is an Alias, the name of the mapping is the real name and not alias name
  90.         $mapping array_shift($data);
  91.         if (isset($mapping['mappings'])) {
  92.             return $mapping['mappings'];
  93.         }
  94.         return [];
  95.     }
  96.     /**
  97.      * Returns the index settings object.
  98.      *
  99.      * @return \Elastica\Index\Settings Settings object
  100.      */
  101.     public function getSettings()
  102.     {
  103.         return new IndexSettings($this);
  104.     }
  105.     /**
  106.      * Uses _bulk to send documents to the server.
  107.      *
  108.      * @param array|\Elastica\Document[] $docs Array of Elastica\Document
  109.      *
  110.      * @return \Elastica\Bulk\ResponseSet
  111.      *
  112.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
  113.      */
  114.     public function updateDocuments(array $docs)
  115.     {
  116.         foreach ($docs as $doc) {
  117.             $doc->setIndex($this->getName());
  118.         }
  119.         return $this->getClient()->updateDocuments($docs);
  120.     }
  121.     /**
  122.      * Uses _bulk to send documents to the server.
  123.      *
  124.      * @param array|\Elastica\Document[] $docs Array of Elastica\Document
  125.      *
  126.      * @return \Elastica\Bulk\ResponseSet
  127.      *
  128.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
  129.      */
  130.     public function addDocuments(array $docs)
  131.     {
  132.         foreach ($docs as $doc) {
  133.             $doc->setIndex($this->getName());
  134.         }
  135.         return $this->getClient()->addDocuments($docs);
  136.     }
  137.     /**
  138.      * Deletes entries in the db based on a query.
  139.      *
  140.      * @param \Elastica\Query|\Elastica\Query\AbstractQuery|string|array $query   Query object or array
  141.      * @param array                                                      $options Optional params
  142.      *
  143.      * @return \Elastica\Response
  144.      *
  145.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/docs-delete-by-query.html
  146.      */
  147.     public function deleteByQuery($query, array $options = [])
  148.     {
  149.         $query Query::create($query)->getQuery();
  150.         $endpoint = new DeleteByQuery();
  151.         $endpoint->setBody(['query' => is_array($query) ? $query $query->toArray()]);
  152.         $endpoint->setParams($options);
  153.         return $this->requestEndpoint($endpoint);
  154.     }
  155.     /**
  156.      * Deletes the index.
  157.      *
  158.      * @return \Elastica\Response Response object
  159.      */
  160.     public function delete()
  161.     {
  162.         return $this->requestEndpoint(new Delete());
  163.     }
  164.     /**
  165.      * Uses _bulk to delete documents from the server.
  166.      *
  167.      * @param array|\Elastica\Document[] $docs Array of Elastica\Document
  168.      *
  169.      * @return \Elastica\Bulk\ResponseSet
  170.      *
  171.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
  172.      */
  173.     public function deleteDocuments(array $docs)
  174.     {
  175.         foreach ($docs as $doc) {
  176.             $doc->setIndex($this->getName());
  177.         }
  178.         return $this->getClient()->deleteDocuments($docs);
  179.     }
  180.     /**
  181.      * Optimizes search index.
  182.      *
  183.      * Detailed arguments can be found here in the link
  184.      *
  185.      * @param array $args OPTIONAL Additional arguments
  186.      *
  187.      * @return array Server response
  188.      *
  189.      * @deprecated Replaced by forcemerge
  190.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-optimize.html
  191.      */
  192.     public function optimize($args = [])
  193.     {
  194.         trigger_error('Deprecated: Elastica\Index::optimize() is deprecated and will be removed in further Elastica releases. Use Elastica\Index::forcemerge() instead.'E_USER_DEPRECATED);
  195.         return $this->forcemerge($args);
  196.     }
  197.     /**
  198.      * Force merges index.
  199.      *
  200.      * Detailed arguments can be found here in the link
  201.      *
  202.      * @param array $args OPTIONAL Additional arguments
  203.      *
  204.      * @return Response
  205.      *
  206.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html
  207.      */
  208.     public function forcemerge($args = [])
  209.     {
  210.         $endpoint = new ForceMerge();
  211.         $endpoint->setParams($args);
  212.         return $this->requestEndpoint($endpoint);
  213.     }
  214.     /**
  215.      * Refreshes the index.
  216.      *
  217.      * @return \Elastica\Response Response object
  218.      *
  219.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
  220.      */
  221.     public function refresh()
  222.     {
  223.         return $this->requestEndpoint(new Refresh());
  224.     }
  225.     /**
  226.      * Creates a new index with the given arguments.
  227.      *
  228.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
  229.      *
  230.      * @param array      $args    OPTIONAL Arguments to use
  231.      * @param bool|array $options OPTIONAL
  232.      *                            bool=> Deletes index first if already exists (default = false).
  233.      *                            array => Associative array of options (option=>value)
  234.      *
  235.      * @throws \Elastica\Exception\InvalidException
  236.      * @throws \Elastica\Exception\ResponseException
  237.      *
  238.      * @return \Elastica\Response Server response
  239.      */
  240.     public function create(array $args = [], $options null)
  241.     {
  242.         if (is_bool($options) && $options) {
  243.             try {
  244.                 $this->delete();
  245.             } catch (ResponseException $e) {
  246.                 // Table can't be deleted, because doesn't exist
  247.             }
  248.         } elseif (is_array($options)) {
  249.             foreach ($options as $key => $value) {
  250.                 switch ($key) {
  251.                     case 'recreate':
  252.                         try {
  253.                             $this->delete();
  254.                         } catch (ResponseException $e) {
  255.                             // Table can't be deleted, because doesn't exist
  256.                         }
  257.                         break;
  258.                     default:
  259.                         throw new InvalidException('Invalid option '.$key);
  260.                         break;
  261.                 }
  262.             }
  263.         }
  264.         $endpoint = new Create();
  265.         $endpoint->setBody($args);
  266.         return $this->requestEndpoint($endpoint);
  267.     }
  268.     /**
  269.      * Checks if the given index is already created.
  270.      *
  271.      * @return bool True if index exists
  272.      */
  273.     public function exists()
  274.     {
  275.         $response $this->requestEndpoint(new Exists());
  276.         return $response->getStatus() === 200;
  277.     }
  278.     /**
  279.      * @param string|array|\Elastica\Query $query
  280.      * @param int|array                    $options
  281.      * @param BuilderInterface             $builder
  282.      *
  283.      * @return Search
  284.      */
  285.     public function createSearch($query ''$options nullBuilderInterface $builder null)
  286.     {
  287.         $search = new Search($this->getClient(), $builder);
  288.         $search->addIndex($this);
  289.         $search->setOptionsAndQuery($options$query);
  290.         return $search;
  291.     }
  292.     /**
  293.      * Searches in this index.
  294.      *
  295.      * @param string|array|\Elastica\Query $query   Array with all query data inside or a Elastica\Query object
  296.      * @param int|array                    $options OPTIONAL Limit or associative array of options (option=>value)
  297.      *
  298.      * @return \Elastica\ResultSet with all results inside
  299.      *
  300.      * @see \Elastica\SearchableInterface::search
  301.      */
  302.     public function search($query ''$options null)
  303.     {
  304.         $search $this->createSearch($query$options);
  305.         return $search->search();
  306.     }
  307.     /**
  308.      * Counts results of query.
  309.      *
  310.      * @param string|array|\Elastica\Query $query Array with all query data inside or a Elastica\Query object
  311.      *
  312.      * @return int number of documents matching the query
  313.      *
  314.      * @see \Elastica\SearchableInterface::count
  315.      */
  316.     public function count($query '')
  317.     {
  318.         $search $this->createSearch($query);
  319.         return $search->count();
  320.     }
  321.     /**
  322.      * Opens an index.
  323.      *
  324.      * @return \Elastica\Response Response object
  325.      *
  326.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html
  327.      */
  328.     public function open()
  329.     {
  330.         return $this->requestEndpoint(new Open());
  331.     }
  332.     /**
  333.      * Closes the index.
  334.      *
  335.      * @return \Elastica\Response Response object
  336.      *
  337.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html
  338.      */
  339.     public function close()
  340.     {
  341.         return $this->requestEndpoint(new Close());
  342.     }
  343.     /**
  344.      * Returns the index name.
  345.      *
  346.      * @return string Index name
  347.      */
  348.     public function getName()
  349.     {
  350.         return $this->_name;
  351.     }
  352.     /**
  353.      * Returns index client.
  354.      *
  355.      * @return \Elastica\Client Index client object
  356.      */
  357.     public function getClient()
  358.     {
  359.         return $this->_client;
  360.     }
  361.     /**
  362.      * Adds an alias to the current index.
  363.      *
  364.      * @param string $name    Alias name
  365.      * @param bool   $replace OPTIONAL If set, an existing alias will be replaced
  366.      *
  367.      * @return \Elastica\Response Response
  368.      *
  369.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
  370.      */
  371.     public function addAlias($name$replace false)
  372.     {
  373.         $data = ['actions' => []];
  374.         if ($replace) {
  375.             $status = new Status($this->getClient());
  376.             foreach ($status->getIndicesWithAlias($name) as $index) {
  377.                 $data['actions'][] = ['remove' => ['index' => $index->getName(), 'alias' => $name]];
  378.             }
  379.         }
  380.         $data['actions'][] = ['add' => ['index' => $this->getName(), 'alias' => $name]];
  381.         $endpoint = new Update();
  382.         $endpoint->setBody($data);
  383.         return $this->getClient()->requestEndpoint($endpoint);
  384.     }
  385.     /**
  386.      * Removes an alias pointing to the current index.
  387.      *
  388.      * @param string $name Alias name
  389.      *
  390.      * @return \Elastica\Response Response
  391.      *
  392.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
  393.      */
  394.     public function removeAlias($name)
  395.     {
  396.         $endpoint = new \Elasticsearch\Endpoints\Indices\Alias\Delete();
  397.         $endpoint->setName($name);
  398.         return $this->requestEndpoint($endpoint);
  399.     }
  400.     /**
  401.      * Returns all index aliases.
  402.      *
  403.      * @return array Aliases
  404.      */
  405.     public function getAliases()
  406.     {
  407.         $endpoint = new \Elasticsearch\Endpoints\Indices\Alias\Get();
  408.         $endpoint->setName('*');
  409.         $responseData $this->requestEndpoint($endpoint)->getData();
  410.         if (!isset($responseData[$this->getName()])) {
  411.             return [];
  412.         }
  413.         $data $responseData[$this->getName()];
  414.         if (!empty($data['aliases'])) {
  415.             return array_keys($data['aliases']);
  416.         }
  417.         return [];
  418.     }
  419.     /**
  420.      * Checks if the index has the given alias.
  421.      *
  422.      * @param string $name Alias name
  423.      *
  424.      * @return bool
  425.      */
  426.     public function hasAlias($name)
  427.     {
  428.         return in_array($name$this->getAliases());
  429.     }
  430.     /**
  431.      * Clears the cache of an index.
  432.      *
  433.      * @return \Elastica\Response Response object
  434.      *
  435.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-clearcache.html
  436.      */
  437.     public function clearCache()
  438.     {
  439.         // TODO: add additional cache clean arguments
  440.         return $this->requestEndpoint(new Clear());
  441.     }
  442.     /**
  443.      * Flushes the index to storage.
  444.      *
  445.      * @param array $options
  446.      *
  447.      * @return Response Response object
  448.      *
  449.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-flush.html
  450.      */
  451.     public function flush(array $options = [])
  452.     {
  453.         $endpoint = new Flush();
  454.         $endpoint->setParams($options);
  455.         return $this->requestEndpoint($endpoint);
  456.     }
  457.     /**
  458.      * Can be used to change settings during runtime. One example is to use it for bulk updating.
  459.      *
  460.      * @param array $data Data array
  461.      *
  462.      * @return \Elastica\Response Response object
  463.      *
  464.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html
  465.      */
  466.     public function setSettings(array $data)
  467.     {
  468.         $endpoint = new Put();
  469.         $endpoint->setBody($data);
  470.         return $this->requestEndpoint($endpoint);
  471.     }
  472.     /**
  473.      * Makes calls to the elasticsearch server based on this index.
  474.      *
  475.      * @param string       $path   Path to call
  476.      * @param string       $method Rest method to use (GET, POST, DELETE, PUT)
  477.      * @param array|string $data   OPTIONAL Arguments as array or encoded string
  478.      * @param array        $query  OPTIONAL Query params
  479.      *
  480.      * @return \Elastica\Response Response object
  481.      */
  482.     public function request($path$method$data = [], array $query = [])
  483.     {
  484.         $path $this->getName().'/'.$path;
  485.         return $this->getClient()->request($path$method$data$query);
  486.     }
  487.     /**
  488.      * Makes calls to the elasticsearch server with usage official client Endpoint based on this index.
  489.      *
  490.      * @param AbstractEndpoint $endpoint
  491.      *
  492.      * @return Response
  493.      */
  494.     public function requestEndpoint(AbstractEndpoint $endpoint)
  495.     {
  496.         $cloned = clone $endpoint;
  497.         $cloned->setIndex($this->getName());
  498.         return $this->getClient()->requestEndpoint($cloned);
  499.     }
  500.     /**
  501.      * Analyzes a string, or a list of strings.
  502.      *
  503.      * Detailed arguments can be found here in the link
  504.      *
  505.      * @param string[]|string $text String or list of strings to be analyzed
  506.      * @param array           $args OPTIONAL Additional arguments
  507.      *
  508.      * @return array Server response
  509.      *
  510.      * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-analyze.html
  511.      */
  512.     public function analyze($text$args = [])
  513.     {
  514.         $endpoint = new Analyze();
  515.         $endpoint->setBody(['text' => $text]);
  516.         $endpoint->setParams($args);
  517.         $data $this->requestEndpoint($endpoint)->getData();
  518.         // Support for "Explain" parameter, that returns a different response structure from Elastic
  519.         // @see: https://www.elastic.co/guide/en/elasticsearch/reference/current/_explain_analyze.html
  520.         if (isset($args['explain']) && $args['explain']) {
  521.             return $data['detail'];
  522.         }
  523.         return $data['tokens'];
  524.     }
  525. }