programing

CSV 또는 JSON을 Firebase 클라우드 Firestore로 가져오는 방법

jooyons 2023. 6. 9. 22:01
반응형

CSV 또는 JSON을 Firebase 클라우드 Firestore로 가져오는 방법

파이어베이스 실시간 데이터베이스에서와 같이 파이어베이스 클라우드 파이어스토어로 CSV 또는 JSON을 가져오는 방법이 있습니까?

여기에 이미지 설명 입력

일반 솔루션

JSON 업로드를 허용하는 스크립트에 대한 많은 테이크를 찾았지만 그 중 어떤 것도 서브 컬렉션을 허용하지 않았습니다.위의 스크립트는 모든 수준의 중첩 및 하위 컬렉션을 처리합니다.또한 문서에 자체 데이터 및 하위 컬렉션이 있는 경우에도 처리합니다.이는 컬렉션이 개체의 배열/개체(빈 개체 또는 배열 포함)라는 가정을 기반으로 합니다.

스크립트를 실행하려면 npm과 노드가 설치되어 있어야 합니다.그런 다음 코드를 실행합니다.node <name of the file>클라우드 펑션으로 배포할 필요가 없습니다.

const admin = require('../functions/node_modules/firebase-admin');
const serviceAccount = require("./service-key.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<your-database-name>.firebaseio.com"
});

const data = require("./fakedb.json");

/**
 * Data is a collection if
 *  - it has a odd depth
 *  - contains only objects or contains no objects.
 */
function isCollection(data, path, depth) {
  if (
    typeof data != 'object' ||
    data == null ||
    data.length === 0 ||
    isEmpty(data)
  ) {
    return false;
  }

  for (const key in data) {
    if (typeof data[key] != 'object' || data[key] == null) {
      // If there is at least one non-object item in the data then it cannot be collection.
      return false;
    }
  }

  return true;
}

// Checks if object is empty.
function isEmpty(obj) {
  for(const key in obj) {
    if(obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}

async function upload(data, path) {
  return await admin.firestore()
    .doc(path.join('/'))
    .set(data)
    .then(() => console.log(`Document ${path.join('/')} uploaded.`))
    .catch(() => console.error(`Could not write document ${path.join('/')}.`));
}

/**
 *
 */
async function resolve(data, path = []) {
  if (path.length > 0 && path.length % 2 == 0) {
    // Document's length of path is always even, however, one of keys can actually be a collection.

    // Copy an object.
    const documentData = Object.assign({}, data);

    for (const key in data) {
      // Resolve each collection and remove it from document data.
      if (isCollection(data[key], [...path, key])) {
        // Remove a collection from the document data.
        delete documentData[key];
        // Resolve a colleciton.
        resolve(data[key], [...path, key]);
      }
    }

    // If document is empty then it means it only consisted of collections.
    if (!isEmpty(documentData)) {
      // Upload a document free of collections.
      await upload(documentData, path);
    }
  } else {
    // Collection's length of is always odd.
    for (const key in data) {
      // Resolve each collection.
      await resolve(data[key], [...path, key]);
    }
  }
}

resolve(data);

이 작업을 수행하려면 사용자 지정 스크립트가 필요합니다.

Firebase 라이브러리에서 중첩된 데이터 배열가져올없는Firebase 관리 SDK를 기반으로 작성했습니다.

const admin = require('./node_modules/firebase-admin');
const serviceAccount = require("./service-key.json");

const data = require("./data.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://YOUR_DB.firebaseio.com"
});

data && Object.keys(data).forEach(key => {
    const nestedContent = data[key];

    if (typeof nestedContent === "object") {
        Object.keys(nestedContent).forEach(docTitle => {
            admin.firestore()
                .collection(key)
                .doc(docTitle)
                .set(nestedContent[docTitle])
                .then((res) => {
                    console.log("Document successfully written!");
                })
                .catch((error) => {
                    console.error("Error writing document: ", error);
                });
        });
    }
});

업데이트: 저는 이 주제에 대한 기사를 썼습니다 - Firestore에 데이터 채우기

없습니다. 지금은 직접 스크립트를 작성해야 합니다.

Maciej Caputa에서 제공하는 General Solution을 사용했습니다.감사합니다(:

여기 몇 가지 힌트가 있습니다.Ionic Firebase 응용 프로그램이 해당 솔루션 내의 functions 폴더에 필요한 Firebase 노드 모듈과 함께 설치되어 있다고 가정합니다.이것은 표준 Ionic Firebase 설치입니다.스크립트와 데이터를 동일한 수준으로 유지하기 위해 가져오기 폴더를 만들었습니다.

폴더 계층

myIonicApp
    functions
        node_modules
            firebase-admin
ImportFolder
    script.js
    FirebaseIonicTest-a1b2c3d4e5.json
    fileToImport.json

스크립트 매개 변수

const admin = require('../myIonicApp/functions/node_modules/firebase-admin'); //path to firebase-admin module
const serviceAccount = require("./FirebaseTest-xxxxxxxxxx.json"); //service account key file

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://fir-test-xxxxxx.firebaseio.com" //Your domain from the hosting tab
});

[호스팅] 탭의 도메인 이름

서비스 계정 키 파일 만들기

  • 프로젝트의 Firebase 콘솔에서 Project Overview 항목 옆에 있는 기어 아이콘을 클릭하고 Users and permissions(사용자 및 권한)를 선택합니다.
  • 화면 아래쪽에서 고급 권한 설정을 클릭합니다.

Google 클라우드 플랫폼 콘솔 액세스

  • 그러면 Google Cloud Platform Console의 다른 탭이 열립니다.
  • 왼쪽에서 서비스 계정 항목을 선택합니다.
  • 기존 서비스 계정에 대한 서비스 계정 생성

앱 엔진 기본 서비스 계정에 키를 추가했습니다.

키 만들기 기능은 키를 JSON 파일로 다운로드하는 기능을 제공합니다.

서비스 계정 키 만들기

JSON 데이터 구조

제공된 스크립트를 사용하려면 데이터 구조가 다음과 같아야 합니다.

{
  "myCollection" : {
    "UniqueKey1" : {
      "field1" : "foo",
      "field2" : "bar"
    },{
    "UniqueKey2" : {
      "field1" : "fog",
      "field2" : "buzz"
    }...
}

참고로.저는 Firestore에서 데이터를 가져오고 내보낼 수 있는 기능을 작성했습니다.

https://github.com/dalenguyen/firestore-import-export (계속)

2023년 업데이트:

대신 이 패키지를 사용하십시오.감사합니다, @Webber.

https://github.com/dalenguyen/firestore-backup-restore

https://gist.github.com/JoeRoddy/1c706b77ca676bfc0983880f6e9aa8c8

이것은 객체(일반적으로 오래된 방화벽 기반 json이 설정된 정도)에 대해 작동해야 합니다.이미 Firestore로 구성된 앱에 해당 코드를 추가할 수 있습니다.

정확한 JSON 파일을 가리키고 있는지 확인하십시오.

행운을 빕니다.

Python의 이러한 해결 방법은 일부 사용자에게 도움이 될 수 있습니다.먼저 Panda를 사용하여 json 또는 csv를 데이터 프레임으로 변환한 다음 데이터 프레임을 사전으로 변환하고 사전을 Firestore에 업로드합니다.

import firebase_admin as fb
from firebase_admin import firestore
import pandas as pd

cred = fb.credentials.Certificate('my_credentials_certificate.json')
default_app = fb.initialize_app(cred)
db = firestore.client()

df = pd.read_csv('data.csv')
dict = df.to_dict(orient='records')

my_doc_ref = db.collection('my_collection').document('my_document')
my_doc_ref.set(dict)

Pandas와 유사한 라이브러리를 사용하는 Javascript 및 기타 언어에서 유사한 해결 방법이 있을 수 있습니다.

지금은 안돼요, 당신은..firestore는 컬렉션을 사용하여 데이터를 다른 형식으로 구성합니다. 각 컬렉션에는 JSON 형식으로 저장되는 일련의 문서가 있습니다.미래에 그들은 JSON을 파이어스토어로 변환하는 도구를 만들 수도 있습니다.참고로 이것을 확인하세요.

:https://cloud.google.com/firestore/docs/concepts/structure-data

****편집 :****

프로세스를 어느 정도 자동화할 수 있습니다. 즉, CSV 또는 JSON 데이터 필드만 Cloud Firestore DB에 푸시하는 모의 소프트웨어를 작성할 수 있습니다.데이터베이스 전체를 마이그레이션하여 DB를 검색하고 Firestore에 푸시하는 간단한 앱을 만들었습니다.

var admin = require('firebase-admin');

var serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://csvread-d149c.firebaseio.com'
});

const csv = require('csv-parser');  
const fs = require('fs');

const firestore = admin.firestore();

// CSV FILE data.csv

// Name,Surname,Age,Gender
// John,Snow,26,M  
// Clair,White,33,F  
// Fancy,Brown,78,F

fs.createReadStream('data.csv')  
  .pipe(csv())
  .on('data', (row) => {
    console.log(row);
    if(row) {
      firestore.collection('csv').add({
        name: row.Name,
        surname: row.Surname,
        age: row.Age,
        sex: row.Gender
      });
    }
    else {
      console.log('No data')
    }
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
  });

파이어푸라는 유료 GUI 도구가 있습니다.사용해 본 적은 없지만, CSV 파일 가져오기를 포함하여 Firestore를 관리하는 데 매우 유용한 기능인 것 같습니다.

여기에 이미지 설명 입력

이것은 문서의 'id'가 있는 경우 해당 경로에 복사하는 작은 수정입니다.그렇지 않으면 "for" 색인을 사용합니다.

  ...
  ...
  } else {
    // Collection's length of is always odd.
    for (const key in data) {
      // Resolve each collection.
      if (data[key]['id']!==undefined)
        await resolve(data[key], [...path,data[key]['id']])
      else 
        await resolve(data[key], [...path, key]);
    }
  }
}

resolve(data);

1 - 컬렉션만 가져오는 중

컬렉션 이름이 숫자로만 구성되지 않은 경우 다음과 같이 문서 이름을 정의할 수 있습니다.


    ...
    ...

    } else {
        // Collection's length of is always odd.
        for (const key in data) {
          // // Resolve each collection.

          // If key is a number it means that it is not a collection
          // The variable id in this case will be the name of the document field or you 
          // can generate randomly
          let id = !isNaN(key) ? data[key].id : key;

          await resolve(data[key], [...path, id]);
        }
      }
    }

2 - 수입품 수집 및 하위 수집

위의 예와 마찬가지로 하위 컬렉션의 이름은 숫자만 포함할 수 없습니다.

    ...
    ...

    for (const key in data) {
      // Resolve each collection and remove it from document data.
      if (isCollection(data[key], [...path, key])) {
        // Remove a collection from the document data.
        delete documentData[key];

        // If key is a number it means that it is not a collection
        // The variable id in this case will be the name of the document field or you 
        // can generate randomly
        let id = !isNaN(key) ? data[key].id : key;

        // Resolve a colleciton.
        resolve(data[key], [...path, id]);
      }
    }

    ...
    ...

참고: @Maciej Caputa 코드의 변경 사항

라이브러리는 https://www.npmjs.com/package/csv-to-firestore 를 사용할 수 있습니다.

이 명령을 사용하여 이 라이브러리 설치npm i -g csv-to-firestore

이 스크립트를 당신의 ./message 안에 넣습니다.

    module.exports = {
      path: "./scripts/palabrasOutput.csv",
      firebase: {
        credential: "./scripts/serviceAccount.json",
        collection: "collectionInFirestore",
      },
      mapper: (dataFromCSV) => {
        return dataFromCSV;
      },
    };

실행:

csv-to-firestore --config ./scripts/csvToFirestore.js

btw: 새 개인 키(firestore의 Service account 섹션에 있는 파일)를 생성하고 해당 파일을 /scripts 폴더에 넣고 serviceAccount.json의 이름을 변경합니다.

언급URL : https://stackoverflow.com/questions/46640981/how-to-import-csv-or-json-to-firebase-cloud-firestore

반응형