gpt4 book ai didi

Symfony2 FOSElasticaBundle 更新与更新实体相关的所有实体的索引

转载 作者:行者123 更新时间:2023-12-02 09:35:30 24 4
gpt4 key购买 nike

我在项目中使用 FOSElasticaBundle 和 Doctrine,并且我的代码适用于使用 Doctrine 生命周期事件的选择性索引更新。我遇到的问题是我是否单独更新相关实体。

例如,一个人可能通过多对多关系与一家公司相关。如果我直接通过公司实体更新公司名称,那么与公司相关的人员的索引将过时,并且仍然与公司的旧名称相关。

我对如何处理这个问题有点迷茫,有人有什么建议吗?我是否必须依赖计划的索引更新并同时处理不准确的索引数据,或者是否有一种方法可以为与已更新的实体相关的实体调用更新。

我依靠 JMSSerializer 组来建立映射。我意识到,从长远来看,这可能不是最好的做事方式。

最佳答案

我也遇到过同样的问题。看来我的安装(Symfony 2.5.4 和 FOSElastica 3.0.4)与你的安装有很大不同。因此,代码运行时遇到了一些问题。我发布我的解决方案,因为它可能对其他开发人员有用。

监听器不在 FOS\ElasticaBundle\Doctrine\ORM\中,而是在 FOS\ElasticaBundle\Doctrine 中。所以你必须使用那个。另外,我必须使用 Doctrine\Common\EventArgs 而不是 Doctrine\ORM\Event\LifecycleEventArgs,因为否则我自己的 postUpdate 方法与 BaseListener 中的方法不兼容。

在我的应用程序中,一门类(class)(研讨会)可以有很多 session ,但在这个项目中,elastica 将只使用这些 session 。应用程序需要了解与类(class)相关的类(class)的一些详细信息。所以,这是我的代码:

在 config.yml 中,我的 elastica bundle 配置如下所示:

fos_elastica:
clients:
default: { host: localhost, port: 9200 }
indexes:
courses:
index_name: courses
types:
session:
mappings:
id: ~
name: ~
course:
type: "nested"
properties:
id: ~
name: ~

再远一点,仍然在config.yml中

services:
# some other services here

fos_elastica.listener.courses.course:
class: XXX\CourseBundle\EventListener\ElasticaCourseListener
arguments:
- @fos_elastica.object_persister.courses.course
- ['postPersist', 'postUpdate', 'preRemove']
- @fos_elastica.indexable
calls:
- [ setContainer, ['@service_container', @fos_elastica.object_persister.courses.session ] ]
tags:
- { name: 'doctrine.event_subscriber' }

我自己的监听器 (XXX\CourseBundle\EventListener\ElasticaCourseListener) 看起来像这样:

<?php

namespace XXX\CourseBundle\EventListener;

use Doctrine\Common\EventArgs;
use FOS\ElasticaBundle\Doctrine\Listener as BaseListener;
use FOS\ElasticaBundle\Persister\ObjectPersister;
use Symfony\Component\DependencyInjection\ContainerInterface;
use XXX\CourseBundle\Entity\Course;

class ElasticaCourseListener extends BaseListener
{
private $container;
private $objectPersisterSession;

public function setContainer(ContainerInterface $container, ObjectPersister $objectPersisterSession)
{
$this->container = $container;
$this->objectPersisterSession = $objectPersisterSession;
}

public function postUpdate(EventArgs $args)
{
$entity = $args->getEntity();

if ($entity instanceof Course) {
$this->scheduledForUpdate[] = $entity;
foreach ($entity->getSessions() as $session) {
$this->objectPersisterSession->replaceOne($session);
}
}
}
}

现在,当我更新类(class)时,它将作为 ElasticSearch 中的嵌套对象进行更新;-)

关于Symfony2 FOSElasticaBundle 更新与更新实体相关的所有实体的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21909763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com