Validation 在插入BigQuery表之前检查数据是否已经存在(使用Python)

Validation 在插入BigQuery表之前检查数据是否已经存在(使用Python),validation,google-bigquery,Validation,Google Bigquery,我正在设置一个每日cron作业,将一行附加到BigQuery表(使用Python),但是,正在插入重复的数据。我在网上搜索过,我知道有一种方法可以手动获取数据,但我想看看是否可以首先避免这种重复 是否有办法首先检查BigQuery表以查看数据记录是否已经存在,以避免插入重复数据?谢谢 代码片段: import webapp2 import logging from googleapiclient import discovery from oath2client.client import Go

我正在设置一个每日cron作业,将一行附加到BigQuery表(使用Python),但是,正在插入重复的数据。我在网上搜索过,我知道有一种方法可以手动获取数据,但我想看看是否可以首先避免这种重复

是否有办法首先检查BigQuery表以查看数据记录是否已经存在,以避免插入重复数据?谢谢

代码片段:

import webapp2
import logging
from googleapiclient import discovery
from oath2client.client import GoogleCredentials

PROJECT_ID = 'foo'
DATASET_ID = 'bar'
TABLE_ID = 'foo_bar_table’

class UpdateTableHandler(webapp2.RequestHandler):
    def get(self):
        credentials = GoogleCredentials.get_application_default()
        service = discovery.build('bigquery', 'v2', credentials=credentials)

    try:

     the_fruits = Stuff.query(Stuff.fruitTotal >= 5).filter(Stuff.fruitColor == 'orange').fetch();

     for fruit in the_fruits:
       #some code here

     basket = dict()
     basket['id'] = fruit.fruitId
     basket['Total'] = fruit.fruitTotal
     basket['PrimaryVitamin'] = fruit.fruitVitamin
     basket['SafeRaw'] = fruit.fruitEdibleRaw
     basket['Color'] = fruit.fruitColor
     basket['Country'] = fruit.fruitCountry

            body = {
                'rows': [
                    {
                        'json': basket,
                        'insertId': str(uuid.uuid4())
                    }
                ]
            }

            response = bigquery_service.tabledata().insertAll(projectId=PROJECT_ID,
                                                              datasetId=DATASET_ID,
                                                              tableId=TABLE_ID,
                                                              body=body).execute(num_retries=5)
            logging.info(response)

    except Exception, e:
        logging.error(e)

app = webapp2.WSGIApplication([
    ('/update_table', UpdateTableHandler),
], debug=True)

测试数据是否已经存在的唯一方法是运行查询

如果表中有大量数据,那么该查询可能会非常昂贵,因此在大多数情况下,我们建议您先插入重复项,然后再合并重复项


正如Zig Mandel在一篇评论中所建议的那样,如果您知道希望查看记录的日期,则可以查询日期分区,但与插入和删除重复项相比,这可能仍然很昂贵。

除非数据在过去24小时内,否则搜索似乎会很昂贵,然后只搜索该分区。