Search code examples
symfonyfoselasticabundle

Add record to Elastic index after flush


I have 3 entity: Employee, UnprocessedEmployee and ViewEmployee (i'ts real view in DB which contain all record from tables employee and unprocessed_employee)

I have Symfony 6 and FOS Elastica 6.2

Index for ViewEmployee from fos_elastica.yaml

employee_handbook:
  index_name: 'employee_list'
  settings:
    refresh_interval: 10s
    index:
      max_result_window: 1000000
  persistence:
    driver: orm
    finder: ~
    identifier: id.toRfc4122
    listener: ~
    model: App\Entity\ViewEmployees
    elastica_to_model_transformer:
      service: app.elastica_to_model.transformer.handbook_employee

I try to add my Employee to index, when user create new entity

$employee = ... create and flush Entity;
 
$employeeId = $employee->getId();

// App\Entity\ViewEmployees from fos elastica config
$viewEmployee = $this->employeeHandbookRepository->findViewEmployeeById($employeeId);

if ($viewEmployee === null) {
    return;
}

$this->entityManager->getEventManager()->dispatchEvent(
    Doctrine\ORM\Events::postFlush,
    new Doctrine\ORM\Event\PostFlushEventArgs($this->entityManager)
);
$this->entityManager->getEventManager()->dispatchEvent(
    Doctrine\ORM\Events::postUpdate,
    new Doctrine\ORM\Event\PostUpdateEventArgs($viewEmployee, $this->entityManager)
);

But after saving the entity, the data does not appear in Elastic. There is data in the PostgreSQL database, all conditions are passed during debugging and the code reaches the dispatchEvent


Solution

  • After a long time of experimentation, I found a solution

    $this->eventDispatcher->dispatchEvent(
            Events::postUpdate,
            new PostUpdateEventArgs($viewEmployee, $this->entityManager)
        );
        $this->eventDispatcher->dispatchEvent(
            Events::postFlush,
            new PostFlushEventArgs($this->entityManager)
        );
    

    The first is postUpdate, and after that is postFlush