types:
product:
mappings:
title: { search_analyzer: custom_search_analyzer, index_analyzer: custom_index_analyzer, type: string }
status:
brand.name: { search_analyzer: custom_search_analyzer, index_analyzer: custom_index_analyzer, type: string }
brand:
type: "nested"
properties:
status: ~
persistence:
driver: orm
model: MyBundle\Entity\Product\Product
provider:
query_builder_method: customProductQueryBuilderElastica
listener: ~
finder: ~
这是我对类型产品的映射。 customProductQueryBuilderElastica 包含仅填充具有有效状态且相关品牌状态有效的产品的代码。如果我从我的管理员更改产品,它的工作正常。
我想要做的是当我将品牌状态更改为无效时,应从ES中删除所有相关产品。
为此,我使用品牌作为产品的嵌套并为explained here创建了监听器,现在我可以自动更改ES中每个产品的品牌状态,但我想在品牌状态时删除此类产品设置为不活动。 如何以更好的方式实现这一目标?
答案 0 :(得分:1)
经过多次尝试。我终于实现了我想要的。我在这里发布我的代码并尝试帮助其他人。
感谢@maercky。我已经参考了他的回答here
这是我的config.yml文件。
types:
product:
mappings:
title: { search_analyzer: custom_search_analyzer, index_analyzer: custom_index_analyzer, type: string }
status:
brand.name: { search_analyzer: custom_search_analyzer, index_analyzer: custom_index_analyzer, type: string }
brand:
type: "nested"
properties:
status: ~
persistence:
driver: orm
model: XXX\MyBundle\Entity\Product\Product
provider:
query_builder_method: customProductQueryBuilderElastica
listener: ~
finder: ~
此代码将转至service.yml
fos_elastica.listener.brand.product:
class: 'XXX\MyBundle\Listener\ElasticaBrandListener'
arguments:
- @fos_elastica.object_persister.search.product
- ['postPersist', 'postUpdate', 'postRemove', 'preRemove']
- @fos_elastica.indexable
calls:
- [ setContainer, [ '@service_container', @fos_elastica.object_persister.search.product ] ]
tags:
- { name: 'doctrine.event_subscriber' }
最后这是我的品牌听众
<?php
namespace XXX\MyBundle\Listener;
use FOS\ElasticaBundle\Doctrine\Listener as BaseListener;
use Doctrine\Common\EventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use XXX\MyBundle\Entity\Supplier\Brand;
use FOS\ElasticaBundle\Persister\ObjectPersister;
class ElasticaBrandListener extends BaseListener
{
/** @var \Symfony\Component\DependencyInjection\ContainerInterface */
private $container;
private $objectPersisterProducts;
public function setContainer(ContainerInterface $container,ObjectPersister $objectPersisterProduct) {
$this->container = $container;
$this->objectPersisterProducts = $objectPersisterProduct;
}
/**
* @param Doctrine\Common\EventArgs $eventArgs
*/
public function postUpdate(EventArgs $eventArgs)
{
/** @var $brand Brand */
$brand = $eventArgs->getEntity();
if ($brand instanceof Brand) {
$this->scheduledForUpdate[] = $brand;
foreach ($brand->getProducts() as $product) {
$brand_status = $brand->getStatus();
$product_status = $product->getStatus();
if($brand_status == 'active' && $product_status == 'active'){
$this->objectPersisterProducts->replaceOne($product);
}else{
$this->objectPersisterProducts->deleteOne($product);
}
}
}
}
}
?>
这一切对我很有用,所以我为其他人做出贡献。