Firestore에서 json 내보내기
Firebase RTB 콘솔에서 json 파일을 다운로드할 수 있는데, Firestore 수집/문서 데이터의 json 파일을 내보낼 수 있는 방법이 있습니까?
제 주요 목표 중 하나는 문서 업데이트 전후의 데이터를 비교하는 것입니다.
방금 Firestore 백업 및 복원 작업을 작성했습니다.내 깃허브에 한번 가보세요.
https://github.com/dalenguyen/firestore-backup-restore
감사해요.
구글은 그것을 필요 이상으로 어렵게 만들었고, 그래서 그 커뮤니티는 해결책을 찾았습니다.가지고 계신다면,npm설치된 경우 다음 작업을 수행할 수 있습니다.
내보내기
npx -p node-firestore-import-export firestore-export -a credentials.json -b backup.json
수입품
npx -p node-firestore-import-export firestore-import -a credentials.json -b backup.json
그렇지 않습니다. 컬렉션을 쿼리하고 모든 것을 루프하는 것과 같은 자체 프로세스를 생각해내야 합니다.
갱신하다
2018년 8월 7일자로 데이터를 GCS 버킷에 덤프할 수 있는 관리형 내보내기 시스템이 있습니다.JSON은 아니지만 클라우드 데이터스토어에서 사용하는 것과 동일한 형식이므로 BigQuery는 이를 이해합니다.즉, BigQuery로 가져올 수 있습니다.
데이터베이스의 컬렉션/문서를 이동하고 모든 것을 하나의 json 파일로 내보내는 도구를 작성했습니다.또한 동일한 구조도 가져옵니다(Firestore 데이터베이스 복제/이동에 유용).몇몇 동료들이 코드를 사용하도록 했기 때문에, 저는 그것을 NPM 패키지로 게시할 것이라고 생각했습니다.자유롭게 사용해 보시고 피드백을 주시기 바랍니다.
https://www.npmjs.com/package/node-firestore-import-export
Python 2 또는 3을 사용하여 솔루션을 원하는 경우.
편집: 이것은 규칙을 백업하지 않습니다.
https://github.com/RobinManoli/python-firebase-admin-firestore-backup 에서 구입하십시오.
먼저 Firebase Admin Python SDK를 설치하고 설정합니다. https://firebase.google.com/docs/admin/setup
그런 다음 Python 환경에 설치합니다.
pip install firebase-admin
Firestore 모듈을 설치합니다.
pip install google-cloud-core
pip install google-cloud-firestore
(ImportError에서: Python용 Cloud Firestore 라이브러리를 가져오지 못함)
파이썬 코드
# -*- coding: UTF-8 -*-
import firebase_admin
from firebase_admin import credentials, firestore
import json
cred = credentials.Certificate('xxxxx-adminsdk-xxxxx-xxxxxxx.json') # from firebase project settings
default_app = firebase_admin.initialize_app(cred, {
'databaseURL' : 'https://xxxxx.firebaseio.com'
})
db = firebase_admin.firestore.client()
# add your collections manually
collection_names = ['myFirstCollection', 'mySecondCollection']
collections = dict()
dict4json = dict()
n_documents = 0
for collection in collection_names:
collections[collection] = db.collection(collection).get()
dict4json[collection] = {}
for document in collections[collection]:
docdict = document.to_dict()
dict4json[collection][document.id] = docdict
n_documents += 1
jsonfromdict = json.dumps(dict4json)
path_filename = "/mypath/databases/firestore.json"
print "Downloaded %d collections, %d documents and now writing %d json characters to %s" % ( len(collection_names), n_documents, len(jsonfromdict), path_filename )
with open(path_filename, 'w') as the_file:
the_file.write(jsonfromdict)
소방서 수출/수입을 위한 npm이 있습니다.
내보낼 프로젝트 이동 -> 프로젝트 설정 -> 서비스 계정 -> 새 개인 키 생성 -> 내보낸 DB.json으로 저장
가져오기 프로젝트 이동 -> 프로젝트 설정 -> 서비스 계정 -> 새 개인 키 생성 -> 가져오기 DB.json으로 저장
파일을 저장한 폴더에서 이 두 명령을 실행합니다.
내보내기: npx -p node-firestore-import-export firestore-export -aexportedDB.json -b backup.json
가져오기: npx -p node-firestore-import-export firestore-import -aimportedDB.json -b backup.json
Firestore는 아직 개발 초기 단계이므로 Firestore와 관련된 정보는 백업 관련 문서를 확인하십시오.
저는 노드-파이어스토어-백업이라는 이 npm 패키지가 쉽고 유용하다는 것을 알게 되었습니다.
로 고는 다음과 .--accountCredentials path/to/credentials/file.json는 https://developers.google.com/identity/protocols/application-default-credentials 의 지침에 따라 얻을 수 있는 서비스 계정 키 json 파일을 참조합니다.
- API 콘솔 자격 증명 페이지로 이동합니다.
- 프로젝트 드롭다운에서 프로젝트를 선택합니다.
- 자격 증명 페이지에서 자격 증명 생성 드롭다운을 선택한 다음 서비스 계정 키를 선택합니다.
- 서비스 계정 드롭다운에서 기존 서비스 계정을 선택하거나 새 서비스 계정을 생성합니다.
- 키 유형에 대해 JSON 키 옵션을 선택한 다음 만들기를 선택합니다.파일이 자동으로 컴퓨터에 다운로드됩니다.
- 방금 다운로드한 *.json 파일을 원하는 디렉토리에 저장합니다.이 디렉토리는 개인 디렉토리여야 하며(다른 사용자에게 액세스 권한을 부여할 수 없음) 웹 서버 코드에 액세스할 수 있어야 합니다.
저한테는 효과가 있어요.
클라우드 함수를 사용하여 Firestore의 모든 데이터를 JSON 형식으로 내보냈습니다.제가 사용했던 기능은 다음과 같습니다.
exports.exportFirestore2Json = functions.https.onRequest((request, response) => {
db.collection("data").get().then(function(querySnapshot) {
const orders = [];
var order = null
querySnapshot.forEach(doc => {
order = doc.data();
orders.push(order);
});
response.send(JSON.stringify(orders))
return true
})
.catch(function(error) {
console.error("Error adding document: ", error);
return false
});
})
그런 다음, https://your-project-id.cloudfunctions.net/exportFirestore2Json 에 가면 다음과 같은 것을 볼 수 있습니다.
예, 가능합니다. 파이어베이스 콘솔에서 청구를 시작할 필요가 없습니다.이것과 함께 https://www.npmjs.com/package/firestore-export-import 이라는 훌륭한 npm 패키지가 있습니다. 당신은 파이어스토어 컬렉션과 문서를 쉽게 내보내고 가져올 수 있습니다.몇 가지 단계만 수행하면 됩니다.
- 서비스 계정 키 가져오기 Open Firebase 콘솔 > 프로젝트 설정 > 서비스 계정 > 새 개인 키 생성
serviceAccountKey.json을 사용하여 다운로드한 파일의 이름을 변경합니다.
-이제 새 폴더와 index.js 파일을 만듭니다.
-이 폴더에 servicekey.json을 붙여넣습니다.
-이제 이 패키지를 설치합니다.
npm install firestore-export-import
OR
yarn add firestore-export-import
파이어베이스에서 데이터 내보내기
const { initializeApp} = require('firestore-export-import')
const serviceAccount = require('./serviceAccountKey.json')
const appName = '[DEFAULT]'
initializeApp(serviceAccount, appName)
const fs = require('fs');
const { backup } = require('firestore-export-import')
//backup('collection name')
backup('users').then((data) =>
{
const json = JSON.stringify(data);
//where collection.json is your output file name.
fs.writeFile('collection.json', json, 'utf8',()=>{
console.log('done');
})
});
node index.js를 실행하면 컬렉션과 문서가 들어 있는 새 collection.json 파일이 나타납니다.조금 지저분해 보인다면 https://codebeautify.org/jsonviewer 으로 온라인 포맷하세요.
이 index.js는 모든 것이 포함된 전체 컬렉션을 내보내고 쿼리를 수행할 수 있는 문서 등을 읽는 매우 기본적인 구성에 불과했습니다.
파이어베이스로 데이터 가져오기
const { initializeApp,restore } = require('firestore-export-import')
const serviceAccount = require('./serviceAccountKey.json')
const appName = '[DEFAULT]'
initializeApp(serviceAccount, appName)
restore('collection.json', {
//where refs is an array of key items
refs: ['users'],
//autoParseDates to parse dates if documents have timestamps
autoParseDates: true,
},()=>{
console.log('done');
})
실행 후에는 수집 사용자로 가득 찬 화재 저장소를 볼 수 있습니다!
당신의 지역에서 소방서로 json을 버려서.DB:
npx -p node-firestore-import-export firestore-import -a credentials.json -b backup.json
Firestore에서 데이터 다운로드용로컬 DB:
npx -p node-firestore-import-export firestore-export -a credentials.json -b backup.json
credentials.json을 생성하려면 프로젝트 설정 -> 서비스 계정 -> 개인 키 생성으로 이동합니다.
- 빈 폴더(firebaseImportExport라고 함)를 생성하고 npm init를 실행합니다.
- 소스 Firebase 프로젝트 -> 설정 -> 서비스 계정으로 이동합니다.
- 새 개인 키 생성 버튼을 클릭하고 파일 이름을 source.json으로 변경하여 firebaseImportExport 폴더에 넣습니다.
- 대상 프로젝트에 대해 동일한 작업(2단계 및 3단계)을 수행하고 파일 이름을 destination.json으로 변경합니다.
- 설치
npm i firebase-adminnpm 패키지 - 인덱스에 다음 코드를 기록합니다.js
const firebase = require('firebase-admin');
var serviceAccountSource = require("./source.json");
var serviceAccountDestination = require("./destination.json");
const sourceAdmin = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccountSource),
databaseURL: "https://**********.firebaseio.com" // replace with source
});
const destinationAdmin = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccountDestination),
databaseURL: "https://$$$$$.firebaseio.com"
}, "destination");
const collections = [ "books", "authors", ...]; // replace with your collections
var source = sourceAdmin.firestore();
var destination = destinationAdmin.firestore();
collections.forEach(colName => {
source.collection(colName).get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
destination.collection(colName).doc(doc.id).set({...doc.data()});
});
});
});
REST API를 통해 JSON으로 문서를 다운로드할 수도 있습니다.
다음은 Cloud SDK와 함께 curl을 사용하여 액세스 토큰을 얻는 예입니다.
curl -H "Authorization: Bearer "$(gcloud auth print-access-token) \
"https://firestore.googleapis.com/v1/projects/$PROJECT/databases/(default)/documents/$COLLECTION/$DOCUMENT"
클라이언트측 파이어베이스 앱(React, Angular 등)을 엽니다.이 코드를 사용하여 콘솔을 기록하고 복사
const products = await db
.collection("collectionName")
.where("time", ">", new Date("2020-09-01"))
.get()
const json = JSON.stringify(products.docs.map((doc) => ({ ...doc.data() })))
console.log(json)
저는 더 쉬운 해결책을 찾았습니다.파이어푸라고 불리는 도구가 있습니다.여기에는 모든 수집 문서와 여러 공급자(전자 메일 및 암호, 전화 번호, 구글, 페이스북 등)가 생성된 사용자가 나열됩니다.JSON & CSV로 데이터를 내보낼 수 있으며 Table, Tree, JSON과 같은 단순화된 형식으로 데이터를 볼 수 있습니다.
참고:- Firebase 콘솔에서 데이터를 가져오거나 내보내기 위한 모든 프로세스를 수행할 필요는 없습니다.
언급URL : https://stackoverflow.com/questions/46617960/export-json-from-firestore
'programing' 카테고리의 다른 글
| VueX 및 스크립트 설정과 함께 양식을 사용하는 방법v-model을 사용합니까? (0) | 2023.07.18 |
|---|---|
| 워드프레스에 로그인한 사용자 목록? (0) | 2023.07.18 |
| try/catch를 사용하지 않고 Python Enum에 int 값이 있는지 테스트하려면 어떻게 해야 합니까? (0) | 2023.07.18 |
| SQLAlchemy ORM을 사용하여 데이터베이스를 효율적으로 업데이트 (0) | 2023.07.18 |
| 왜 그들은 px대신에? (0) | 2023.07.18 |
