dousuo8400 2016-04-26 13:39
浏览 50

将大型Doctrine 2查询结果流输出

In my project I have an API call that potentially should return tens of thousands records.

The data should be returned in one chunk. No pagination is allowed by API design.

Source data is queried from MySQL using Doctrine 2 DQL and consists of several linked objects per record. At the moment the query result is around 25'000 records. I've optimised the SQL query. It runs within milliseconds so no way to optimise here.

The main problem is hydration now. I've tried different types of hydrations and it still takes too long on that amount of data. It also use too much memory.

My idea is to stream data as soon as it is hydrated and then delete data as soon as it is streamed. It will not reduce the time to complete request but it will reduce memory usage and will reduce time before response started.

Is there a way in Doctrine 2 to do some actions after each result row is hydrated?

I.e. I do the big request. I do $qb->getQuery()->getResult() and Doctrine instead of hydrating all data and returning result after each record is hydrated sends data to for example STDOUT and drop objects as soon as data is streamed.

PS: Question is not about how to stream the output of such query to HTTP. I can handle that. Question is about how I can make Doctrine 2 do what I want.

  • 写回答

1条回答 默认 最新

  • doubai9014 2017-01-16 10:55
    关注

    My solution (including a CSV streaming for completeness):

    function getExportableHead()
    {
        // returns array of fields for headings
    }
    
    function getExportableRow($row)
    {
        // returns array of values for a row
    }
    
    $qb = $this->em->getRepository(Item::class)->createSomeQueryBuilder();
    $response = new StreamedResponse(function () use ($qb) {
        $data = $qb->getQuery()->iterate();
        $handle = fopen('php://output', 'w+');
        fputcsv($handle, getExportableHead(), ';');
        while (($object = $data->next()) !== false) {
            $row = getExportableRow($object[0]);
            fputcsv($handle, $row, ';');
            $this->em->detach($object[0]);
        }
        fclose($handle);
    });
    $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
    $response->headers->set('Content-Disposition', 'attachment; filename="out.csv"');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线