flutter 应用程序 - 使用 google 分析数据 api 的趋势帖子

flutter app - trending posts by using google analytics data api

在我的应用程序中,用户创建帖子,我想在特定日期范围内按查看次数、评论等显示热门帖子。为此,我想我可以创建一个自定义事件,如下所示:

await FirebaseAnalytics.instance.logEvent(
    name: "trending_contents",
    parameters: {
      "content_type": EnumToString.convertToString(type),
      "content_id": contentModel.externalId,
      "action_type": "post",
      "point": 3,
    },
  );

我想知道是否可以使用 Google Analytics Data API 获取特定日期范围内的热门帖子?或者有没有更好的方法来获取趋势帖子而不是 google 分析数据 API?

我终于找到了如何使用 Google 分析数据 API 来管理趋势内容的解决方案。如果有人正在寻找满足类似需求的解决方案,这是我目前所做的:

  1. 我在特定情况下发送自定义事件,例如当用户查看内容等时,如下所示。如果您根据预定义的维度和指标(请参阅 API Dimensions & Metrics)使用参数名称,则准备自定义报告将很容易(至少对我来说是这样...)。后来,我在自定义报告中使用 contentType 和 contentId 作为维度,使用 eventValue 作为指标。

     await FirebaseAnalytics.instance.logEvent(
          name: "trending_contents",
          parameters: {
            "content_type": EnumToString.convertToString(event.type),
            "content_id": contentId,
            "action_type": "view",
            "value": 1,
          },
        );
    
  2. 最后,我创建了一个计划的云函数,它每 6 小时运行一次,并根据自定义报告结果填充 firebase 集合。此报告提供特定日期范围内的 contentId,按我在自定义事件中发送的值的总和排序

P.S。你需要创建一个 service account in Google Cloud Console, then generate JSON credentials for it and add the file to your project (see credentialsJsonPath variable below). Then you need to add its email address to google analytics 'Property Access Management' section to access analytics data. To see Google Analytics Data API samples, you can check their GitHub repo

    const { BetaAnalyticsDataClient } = require('@google-analytics/data');
    exports.scheduledTrendingFunction = functions.pubsub.schedule('0 */6 * * *').onRun((context) => {
    const propertyId = process.env.GA_PROPERTY_ID;
    const credentialsJsonPath = process.env.GA_CRENDENTIALS_PATH;
    const analyticsDataClient = new BetaAnalyticsDataClient({
        keyFilename: credentialsJsonPath,
    });

    async function runReport(filterType) {
        // [START analyticsdata_json_credentials_run_report]
        const [response] = await analyticsDataClient.runReport({
            property: `properties/${propertyId}`,
            dateRanges: [
                {
                    startDate: '3daysAgo',
                    endDate: 'today',
                },
            ],
            dimensions: [
                {
                    name: 'contentType',
                },
                {
                    name: 'contentId'
                }
            ],
            metrics: [
                {
                    name: 'eventValue'
                },
            ],
            dimensionFilter: {
                andGroup: {
                    expressions: [
                        {
                            filter: {
                                fieldName: "eventName",
                                inListFilter: {
                                    values: ["trending_contents"]
                                }
                            }
                        },
                        {
                            filter: {
                                fieldName: "contentType",
                                inListFilter: {
                                    values: [filterType]
                                }
                            }
                        }
                    ]
                }
            },
            offset: 0,
            limit: 20,
            orderBys: [
                {
                    desc: true,
                    metric: {
                        metricName: "eventValue"
                    }
                }
            ]
        });
        // [END analyticsdata_json_credentials_run_report]

        const batch = admin.firestore().batch();

        // BATCH: delete
        const trendRef = admin.firestore().collection('trends').doc(filterType);
        batch.delete(trendRef);

        const subTrendRef = admin.firestore().collection('trends').doc(filterType).collection('trendContents');
        
        // console.log(response);
        response.rows.forEach((row, index) => {
            // BATCH: add each contentId to trend
            const contentId = row['dimensionValues']['1']['value'];
            batch.set(subTrendRef.doc(contentId), {priority: index + 1});
        });

        // Commit the batch
        await batch.commit();
    }

    runReport("book");

    return null;
    });