编程语言
首页 > 编程语言> > python-是否可以编写BigQuery来检索PyPI下载随时间推移的分箱计数?

python-是否可以编写BigQuery来检索PyPI下载随时间推移的分箱计数?

作者:互联网

以下代码是针对Google的BigQuery的SQL查询,该查询计算最近30天内我的PyPI软件包已下载的次数.

#standardSQL
SELECT COUNT(*) AS num_downloads
FROM `the-psf.pypi.downloads*`
WHERE file.project = 'pycotools'
  -- Only query the last 30 days of history
  AND _TABLE_SUFFIX
    BETWEEN FORMAT_DATE(
      '%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY))
    AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())

是否可以修改此查询,以便自软件包上传以来每30天获得下载次数?输出将是一个看起来像这样的.csv:

date          count
01-01-2016    10
01-02-2016    20
    ..        ..
01-05-2018    100

解决方法:

我建议使用EXTRACT或MONTH()并仅计算file.project字段,因为它将使查询运行更快.您可以使用的查询是:

#standardSQL
SELECT
  EXTRACT(MONTH FROM _PARTITIONDATE) AS month_, 
  EXTRACT(YEAR FROM _PARTITIONDATE) AS year_,
  count(file.project) as count
FROM
  `the-psf.pypi.downloads*`
WHERE
  file.project= 'pycotools'
    GROUP BY 1, 2
    ORDER by 1 ASC

我尝试使用公共数据集:

#standardSQL
SELECT
  EXTRACT(MONTH FROM pickup_datetime) AS month_, 
  EXTRACT(YEAR FROM pickup_datetime) AS year_,
  count(rate_code) as count
FROM
  `nyc-tlc.green.trips_2015`
WHERE
  rate_code=5
GROUP BY 1, 2
ORDER by 1 ASC

或使用旧版

SELECT
  MONTH(pickup_datetime) AS month_, 
  YEAR(pickup_datetime) AS year_,
  count(rate_code) as count
FROM
  [nyc-tlc:green.trips_2015]
  WHERE
  rate_code=5
  GROUP BY 1, 2
  ORDER by 1 ASC

结果是:

month_  year_   count    
1       2015    34228    
2       2015    36366    
3       2015    42221    
4       2015    41159    
5       2015    41934    
6       2015    39506        

我看到您正在使用_TABLE_SUFFIX,因此,如果要查询分区表,则可以使用_PARTITIONDATE列而不是格式化日期和使用date_sub函数.这也将减少计算时间.

要从one partition查询:

SELECT
  [COLUMN]
FROM
  [DATASET].[TABLE]
WHERE
  _PARTITIONDATE BETWEEN '2016-01-01'
  AND '2016-01-02'

标签:google-bigquery,pypi,python,sql
来源: https://codeday.me/bug/20191109/2010685.html