【问题标题】:How to get Salesforce REST API to paginate?如何让 Salesforce REST API 进行分页?
【发布时间】:2020-03-04 19:40:34
【问题描述】:

我正在为 Salesforce REST API 使用 simple_salesforce python 包装器。我们有数十万条记录,我想拆分 salesforce 数据的拉取,以便不会同时拉取所有记录。

我尝试过传递如下查询:

    results = salesforce_connection.query_all("SELECT my_field FROM my_model limit 2000 offset 50000")

查看从 50K 到 52K 的记录,但收到一个错误,即偏移量只能用于前 2000 条记录。如何使用分页,这样我就不需要一次提取所有记录?

【问题讨论】:

    标签: python-3.x salesforce simple-salesforce


    【解决方案1】:

    您希望使用 salesforce_connection.query(query=SOQL) 和 .query_more(nextRecordsUrl, True)

    由于 .query() 只返回 2000 条记录,您需要使用 .query_more 来获取下一页结果

    来自simple-salesforce docs

    SOQL 查询通过以下方式完成:

    sf.query("SELECT Id, Email FROM Contact WHERE LastName = 'Jones'")
    

    如果由于结果特别大,Salesforce 会在您的查询结果中添加 nextRecordsUrl,例如 "nextRecordsUrl" : "/services/data/v26.0/query/01gD0000002HU6KIAW -2000",您可以使用 ID 或完整 URL 提取附加结果(如果使用完整 URL,则必须传递 'True' 作为第二个参数)

    sf.query_more("01gD0000002HU6KIAW-2000")
    sf.query_more("/services/data/v26.0/query/01gD0000002HU6KIAW-2000", True)
    

    这是一个使用这个的例子

     data = [] # list to hold all the records
    
     SOQL = "SELECT my_field FROM my_model"
    
     results = sf.query(query=SOQL) # api call
    
     ## loop through the results and add the records
     for rec in results['records']:
         rec.pop('attributes', None) # remove extra data
         data.append(rec) # add the record to the list
    
    
     ## check the 'done' attrubite in the response to see if there are more records
     ## While 'done' == False (more records to fetch) get the next page of records
     while(results['done'] == False):
         ## attribute 'nextRecordsUrl' holds the url to the next page of records
         results = sf.query_more(results['nextRecordsUrl', True])
    
         ## repeat the loop of adding the records
         for rec in results['records']:
             rec.pop('attributes', None)
             data.append(rec)
    

    遍历记录并使用数据

     ## loop through the records and get their attribute values
     for rec in data:
         # the attribute name will always be the same as the salesforce api name for that value
         print(rec['my_field'])
    

    就像其他答案所说的那样,这可能会开始消耗大量资源。但如果想要实现页面国家,这是您正在寻找的。​​p>

    也许创建一个更有针对性的 SOQL 语句,以仅获取您的用例在特定时刻所需的记录。

    【讨论】:

      【解决方案2】:

      LIMIT 和 OFFSET 并不是真的要这样使用,如果有人在较早的位置插入或删除记录怎么办(更不用说那里没有 ORDER BY)。顺丰会给你开一个合适的cursor,用吧。

      https://pypi.org/project/simple-salesforce/“查询”的文档说你可以调用query,然后调用query_more,或者你可以转到query_allquery_all 将循环并继续调用 query_more 直到您耗尽光标 - 但这很容易吃掉您的 RAM。

      或者查看批量查询的内容,API 中有一些魔力,但我不知道它是否适合您的用例。这将是异步调用,可能不会在库中实现。它被称为PK Chunking。除非您有数百万条记录,否则我不会打扰。

      【讨论】:

        猜你喜欢
        • 2018-11-24
        • 2021-07-12
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-04
        相关资源
        最近更新 更多