FOSElastica search in multiple entities

55 Views Asked by At

I managed to install FOSElastica in my symfony project, my fos_elsastica.yaml. It works fine with one entity.

fos_elastica:
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        user:
            persistence:
                driver: orm
                model: App\Entity\User
                provider: ~
                finder: ~
            properties:
                email: ~

Is it possible to search in multiples entities, like :

fos_elastica:
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        user:
            persistence:
                driver: orm
                model: App\Entity\User
                provider: ~
                finder: ~
            properties:
                email: ~
        course:
            persistence:
                driver: orm
                model: App\Entity\Course
                provider: ~
                finder: ~
            properties:
                name: ~

If yes how to handle services.yaml file and controller function ? I need to be pointed in right direction.

I tried many things, without any success.

Thanks in advance.

1

There are 1 best solutions below

1
jpvdw On

I'm not sure what the purpose is. There are multiple options for using the different indexes.

If you want to search in another index, you can use the IndexManager, for example:

services:
    app.elasticsearch_search:
        class: App\Service\ElasticsearchSearchService
        arguments:
            - '@fos_elastica.index'


<?php 

namespace App\Service;

use FOS\ElasticaBundle\Manager\IndexManager;

class ElasticsearchSearchService
{
    private $indexManager;

    public function __construct(IndexManager $indexManager)
    {
        $this->indexManager = $indexManager;
    }

    public function searchInIndex(string $index, string $query)
    {
        $index = $this->indexManager->getIndex($index);
        return $userIndex->search($query);
    }
}

But if you want to combine an index, take a look at nested objects: https://github.com/FriendsOfSymfony/FOSElasticaBundle/blob/master/doc/indexes.md#nested-objects-in-foselasticabundle in the documentation. I'm not aware of your entity setup, but here's a small example with the same assumptions.

fos_elastica:
   clients:
       default: { host: localhost, port: 9200 }
   indexes:
       course:
           use_alias: true
           properties:
               id: {type: integer}
               name: {type: text}
               user:
                   type: 'object'
                   properties:
                       id: {type: integer}
                       name: {type: text}
           persistence:
               driver: orm
               model: App\Entity\Course
               provider: ~
               finder: ~