3

I have configured FOSElasticaBundle as follow:

fos_elastica:
    clients:
        default: { host: %elasticsearch_host%, port: %elasticsearch_port%  }
    serializer: ~
    indexes:
        app:
            types:
                tags:
                    serializer:
                        groups: [Default]
                    mappings:
                        name: ~
                    persistence:
                        driver: orm
                        model: AppBundle\Entity\Tag
                        provider: ~
                        listener: ~
                        finder: ~

To my test i have three tags in my database: tag1, tag2, new tag. My entity looks like:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class Tag
 * @package AppBundle\Entity
 *
 * @ORM\Entity
 * @ORM\Table(name="tags")
 */
class Tag
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var int
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    protected $name;

I am searching indexed tags as follows:

$finder = $this->container->get('fos_elastica.finder.app.tags');

$results = [];
if ($query !== null) {
    $results = $finder->find("*" . $query . "*");

    //$results should be serialized, but aren't

    return new Response($results);
}

return new JsonResponse([
    'results' => $results
]);

And my response is: {"results":[{},{},{}]}

Why $results are not serialized ? When I debug $results there are objects inside.

vardius
  • 6,326
  • 8
  • 52
  • 97

3 Answers3

1

You do not understand documentation. As you can read in the following file: https://github.com/FriendsOfSymfony/FOSElasticaBundle/blob/master/Resources/doc/serializer.md

FOSElasticaBundle supports using a Serializer component to serialize your objects to JSON which will be sent directly to the Elasticsearch server. Combined with automatic mapping it means types do not have to be mapped.

FOSElasticaBundle does not return serialized data. It uses serialzier to send serialized data to elasticsearch server. When using serializer you do not have to provide mapping in your config.

Skaza
  • 466
  • 4
  • 13
0

AppBundle\Entity\Tag should implement \JsonSerializable interface so Elastica will handle it grafefully. Some discussions regarding this topic were here: https://github.com/ruflin/Elastica/issues/783

MFix
  • 229
  • 1
  • 5
0

There is a problem with serialize $results to json with JsonResponse.

JsonResponse class is doing simple json_encode inside, so there is no chance to get protected properties.

For example:

<?php

class Data {
protected $id = 1;
public $name = 'foo';
}

var_dump(json_encode(new Data()));

returns {"name":"foo"}

abdulklarapl
  • 184
  • 1
  • 9