9951 explained code solutions for 126 technologies


php-elasticaHow do I use PHP Elastica to create an index?


  1. First, install the Elastica library into your project using composer: composer require "elastica/elastica:~2.0"

  2. Next, create a new \Elastica\Client instance and set the connection parameters for the Elasticsearch server:

$client = new \Elastica\Client(['host' => 'localhost', 'port' => 9200]);
  1. Then, create an index with the desired settings:
$index = $client->getIndex('my_index');
$index->create(array(
    'number_of_shards' => 3,
    'number_of_replicas' => 2
), true);
  1. Finally, add documents to the index:
$doc1 = new \Elastica\Document(1, array('title' => 'Foo', 'content' => 'Foo bar'));
$doc2 = new \Elastica\Document(2, array('title' => 'Bar', 'content' => 'Bar foo'));
$docs = array($doc1, $doc2);

$index->addDocuments($docs);
  1. You can then check the index status with:
$status = $index->getStatus();
echo $status->getNumberOfDocuments(); // Outputs: 2
  1. To learn more about creating and managing indexes with Elastica, refer to the official documentation.

  2. You can also find more detailed examples in the Elastica GitHub repository.

Edit this code on GitHub