Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

As we know the command $ app/console fos:elastica:populate is used to populate elasticsearch index but if you want to populate elasticsearch index programatically then you can use example below. Example depends on FOSElasticaBundle.


Class


use FOS\ElasticaBundle\Index\IndexManager;
use FOS\ElasticaBundle\Index\Resetter;
use FOS\ElasticaBundle\Provider\ProviderInterface;
use FOS\ElasticaBundle\Provider\ProviderRegistry;
use FOS\ElasticaBundle\Elastica\Index;

class ElasticsearchPupulate
{
...

public function populateElasticSearch()
{
/** @var IndexManager $indexManager */
$indexManager = $this->get('fos_elastica.index_manager');
/** @var ProviderRegistry $providerRegistry */
$providerRegistry = $this->get('fos_elastica.provider_registry');
/** @var Resetter $resetter */
$resetter = $this->get('fos_elastica.resetter');

foreach ($indexManager->getAllIndexes() as $indexName => $index) {
/** @var Index $index */
if ($index->exists()) {
$resetter->resetIndex($indexName);
} else {
$index->create();
}

/** @var $providers ProviderInterface[] */
$providers = $providerRegistry->getIndexProviders($indexName);
foreach ($providers as $provider) {
$provider->populate();
}

$indexManager->getIndex($indexName)->refresh();
}
}
}