繁体   English   中英

根据 Python function output 指定的列在 Google BigQuery 上进行查询

[英]Making query on Google BigQuery, depending on column specified by Python function output

我有一个简单的 HTML 页面,要求用户输入并提交他们选择的动物的名称。 然后我有一个 python function 将输入的动物通用名称转换为它的学名,以及它能够转换到哪个分类级别。

例如:Panda -> Ailuropoda melanoleuca, species

我需要下一步的帮助,即获取第一个 python function 的 output,并在 Google 的 BigQuery 上查询 pandas dataframe。 下面是表格预览的屏幕截图。

在此处输入图像描述

下面是我的 main.py 的片段,其中包含查询 function 和底部的 function 调用:

def make_query(taxon, level):
    project_id = "sentinel-system"

    data_frame = pandas_gbq.read_gbq(
        "SELECT * FROM `animal_database.gbif_occurrence` WHERE species=%s LIMIT 10, (taxon)",
        project_id=project_id,
        index_col=level)

    number_of_images = len(data_frame.index)

    credentials = service_account.Credentials.from_service_account_file(
        'Sentinel System-a6746634aad2.json')
    pandas_gbq.context.credentials = credentials
    pandas_gbq.context.project = 'sentinel-system'

    if occurrences > 0:
        print('We found %d images of the animal you searched for!' %(number_of_images))
    else:
        print('Sorry, we couldn''t find any images of the animal you searched for.')
    return 0

taxonomy, level = (common_to_sci('Panda'))
name = taxonomy[-1, -1]
print(name)
print(level)

submission_check = (make_query(name, level))

这个 function 的问题有两个。 首先,较小的问题是运行 main.py 当前显示错误

google.api_core.exceptions.BadRequest: 400 Syntax error: Illegal input character "%" at [1:63]

在使用 python 元组参数的地方是我从这里学到的解决方案,我不确定这个 SQL 查询应该是什么样子。

第二个更普遍的问题是,我知道 SQL 查询需要引用与我的 BigQuery 表中列标题中使用的字符串完全相同的字符串。 但是,如果分类级别不是“种”而是“属/科/目”怎么办? 有没有办法让 SQL 查询在 'level'?= 'species' 的情况下更通用?

在使用@itroulli 的答案反复试验、阅读他们链接的文档并进行一般调整后,这是对我有用的解决方案。

project_id = "sentinel-system"

table = 'animal_database.gbif_occurrence'

query = 'SELECT * FROM {} WHERE {}=\'{}\''.format(table, level, taxon)

data_frame = pandas_gbq.read_gbq(query, project_id=project_id)

使用给定的表,SQL 查询搜索要搜索的正确列(由“level”给出),并在该列下读取由“taxon”给出的动物学名。

根据有关pandas_gbqBigQuery 文档,您应该为参数化查询使用单独的配置变量:

query = "SELECT * FROM `animal_database.gbif_occurrence` WHERE @species=@taxonomy LIMIT 10"

query_config = {
'query': {
    'parameterMode': 'NAMED',
    'queryParameters': [
        {
            'name': 'species',
            'parameterType': {'type': 'STRING'},
            'parameterValue': {'value': level}
        },
        {
            'name': 'taxonomy',
            'parameterType': {'type': 'STRING'},
            'parameterValue': {'value': taxon}
        }
    ]
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM