每个实体一个查询

时间:2013-08-16 09:55:35

标签: php symfony doctrine elasticsearch

想象一下,我们有一个ArrayCollection,包含几个Doctrine Entities实例的Country。还想象一下,我的方法'getName()'实际上是与多种语言的一对多关系(A2lixTranslation支持)......

关键是这个ArrayCollection是从ElasticSearch服务构建的,所以当我检索所有这些实体,迭代它们并打印它们的名字时,只是每个类别的额外查询。

我真的不知道如何管理这种情况,因此150个额外的查询无法维持......

示例实施

$countries = // ArrayCollection of Countries, returned by any mapping system.
foreach ($countries as $country) {

    /**
     * As name is an entity, uses lazy loading in every iteration
     * Because I get collection as it comes, I would like to retrieve
     *   all names in one query. I thought about perform a DQL with a join
     *   of all countries and their names, so Doctrine will catch'em all
     *   but only catch my query and results, and do not identify retrieved
     *   results with my collection, so is not working...
     */
    $name = $country->getName();
    echo $name;
}

// Could be nice do something like this...

$countries = // ArrayCollection of Countries, returned by any mapping system.
$queryBuilder = $this
    ->getDoctrine()
    ->getRepository('ProjectCoreBundle:Country')
    ->createQueryBuilder('c');

/**
 * This query result should only add Cache with results
 */
$queryBuilder
    ->select('c','t')
    ->innerJoin('c.countryName','cn','WITH','c.id = cn.Country')
    ->getQuery()
    ->getResult();        

foreach ($countries as $country) {

    /**
     * At this poing, as Name relation entity is already loaded and cached
     *   lazy load will simply return object ( Any query is performed )
     */
    $name = $country->getName();
    echo $name;
}

2 个答案:

答案 0 :(得分:1)

我建议您查看Elasticsearch中的Multi Search API端点:http://www.elasticsearch.org/guide/reference/api/multi-search/。它允许您准备具有多个查询的单个Web请求; ES将返回与请求中的查询数相同的响应数。它确实减少了网络通信时间。

我认为替代方案是重构您的代码/数据/思维,以允许您执行单个查询以获取您要查找的所有信息,但我认为没有足够的信息可以深入挖掘。

答案 1 :(得分:0)

实际上,我发现已经找到了检索实体翻译的最佳方法。 必须覆盖ElasticSearch DataTransformer。