In most cases we populate elasticsearch index with the data coming from database by running $ app/console fos:elastica:populate command but if you don't have a database you can still populate index with data coming from somewhere else. For that, we use custom built provider service. Example depends on FOSElasticaBundle library.


Config


fos_elastica:
clients:
default: { host: 127.0.0.1, port: 9200 }
indexes:
post_index:
client: default
index_name: post_%kernel.environment%
types:
post:
mappings: ~
persistence:
driver: orm
model: ~
finder: ~
provider:
service: application_search.util.post_provider
listener: ~

Custom provider


namespace Application\SearchBundle\Util;

use Closure;
use Elastica\Document;
use Elastica\Type;
use FOS\ElasticaBundle\Provider\ProviderInterface;

class PostProvider implements ProviderInterface
{
protected $postType;

public function __construct(Type $postType)
{
$this->postType = $postType;
}

public function populate(Closure $loggerClosure = null, array $options = [])
{
$i = 1;
foreach ($this->getData() as $team) {
$document = new Document();
$document->setId($i++);
$document->setData($team);

$this->postType->addDocuments([$document]);
}
}

private function getData()
{
$teams[] = ['name' => 'Fenerbahce'];
$teams[] = ['name' => 'Arsenal'];
$teams[] = ['name' => 'Juventus'];

return $teams;
}
}

Utils.yml


services:
application_search.util.post_provider:
class: Application\SearchBundle\Util\PostProvider
arguments:
- @fos_elastica.index.post_index.post
tags:
- { name: fos_elastica.provider, index: post_index, type: post }

Populate


$ app/console fos:elastica:populate
Resetting post_index
Refreshing post_index
Refreshing post_index

Query


curl -XPOST "http://127.0.0.1:9200/_search?post_dev" -d'
{
"query": {
"bool": {
"must": [
{
"match_all": []
}
]
}
}
}'

Result


{
"took": 1,
"timed_out": false,
"_shards": {
"total": 15,
"successful": 15,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "post_dev",
"_type": "post",
"_id": "1",
"_score": 1,
"_source": {
"name": "Fenerbahce"
}
},
{
"_index": "post_dev",
"_type": "post",
"_id": "2",
"_score": 1,
"_source": {
"name": "Arsenal"
}
},
{
"_index": "post_dev",
"_type": "post",
"_id": "3",
"_score": 1,
"_source": {
"name": "Juventus"
}
}
]
}
}