首页 文章

如何将Firestore数据导出到Google Cloud 端存储?

提问于
浏览
0

我想定期自动将Firestore数据导出到Google Cloud 端存储(以便我可以将其导入BigQuery进行分析) .

Schedule data exports确实概述了一种按计划从Firestore导出数据的方法,但是它是用于在Node.js上运行的JavaScript:我想避免这种情况并且会在服务器端 prefer to stick to an all-Java solution .

Export and import data提供了另一种方法 - 使用 gcloud 命令行实用程序 - 将Firestore数据导出到GCS . 但是,我不想安排脚本在我的笔记本电脑上运行,然后必须确保我的笔记本电脑在正确的时间打开 and 有一个活动的Internet连接 . 我正在寻找一个完全基于App Engine(标准)的解决方案,可以作为 cron 工作 .

在撰写本文时,使用适用于Java的Firebase Admin SDK(版本6.6.0)似乎没有一种编程方式 .

1 回答

  • 1

    答案在于直接使用Firestore REST API .

    在下面的代码中,我使用了Google的HTTP Client Library for Java(无论如何应该是App Engine(标准版)上的默认选项)来进行必要的网络调用 .

    public static final String DEF_GCS_BUCKET_NAME = PROJECT_ID + ".appspot.com";
    
    public static final String FIRESTORE_API_V1BETA2 =
            "https://firestore.googleapis.com/v1beta2";
    
    public static final String FIRESTORE_DB = "/projects/" + PROJECT_ID
            + "/databases/(default)";
    
    public static final String FIRESTORE_EXPORT_GCS_LOC = "gs://"
            + DEF_GCS_BUCKET_NAME + "/firestore-export/";
    
    public static final String FIRESTORE_EXPORT_GCS_ROOT = "firestore-export/";
    
    private static final String FUNC_EXPORT_DOCUMENTS = ":exportDocuments";
    
    @javax.annotation.CheckForNull
    public static Operation exportCollectionToGcs(@lombok.NonNull String collection)
            throws IOException {
    
        AccessToken token = tokenFor(serviceAc());
        Map<String, Object> payload = new HashMap<>();
        payload.put("collectionIds", Arrays.asList(collection));
        payload.put("outputUriPrefix", FIRESTORE_EXPORT_GCS_LOC + collection);
    
        GenericUrl url = new GenericUrl(FIRESTORE_API_V1BETA2 + FIRESTORE_DATABASE
            + FUNC_EXPORT_DOCUMENTS);
        HttpContent content = new JsonHttpContent(jacksonFactory(), payload);
        HttpRequest req = requestFactory().buildPostRequest(url, content);
        req.getHeaders().setAuthorization("Bearer " + token.getTokenValue())
        Operation op = null;
        try {
            HttpResponse res = req.execute();
            // Parse the response JSON to populate an Operation POJO
        } catch (HttpResponseException e) {
            // Handle the error
        }
        return op;
    }
    

    这将启动Firestore Operation以将指定的集合导出到GCS . 如果你想在完成时做某事(或者只是发送/准备报告),你可以get the status of the Operation .

    确保您使用的服务帐户具有必需的权限(在Schedule data exports中描述) .

相关问题