「Gcp/Firebase/Firestore/基本」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「 ==コンソールからfirestoreを作成== #https://console.firebase.google.com #realtimeDatableではなく、データベースの作成ボタンを押す #ロック...」) |
(→1つのレコードのカラムを+1増加) |
||
| (同じ利用者による、間の24版が非表示) | |||
| 行11: | 行11: | ||
==functionsからfirestore呼び出し== | ==functionsからfirestore呼び出し== | ||
===準備=== | ===準備=== | ||
| − | npm i firebase-aimin --save | + | npm i firebase-aimin --save |
===db準備=== | ===db準備=== | ||
| 行32: | 行32: | ||
age: 12 | age: 12 | ||
}; | }; | ||
| − | + | admin.firestore().collection('entries') | |
| − | + | .add(data) | |
| − | + | .then((snapshot) => | |
| − | + | { | |
| + | console.log("insert1 insert"); | ||
}); | }); | ||
| + | response.send("OK"); | ||
}); | }); | ||
</pre> | </pre> | ||
| 行67: | 行69: | ||
===db参照条件=== | ===db参照条件=== | ||
| − | |||
return admin.firestore().collection('entries') | return admin.firestore().collection('entries') | ||
.where('name', '==', 'saburo') | .where('name', '==', 'saburo') | ||
| 行88: | 行89: | ||
.where("name", ">=", "San Francisco") | .where("name", ">=", "San Francisco") | ||
.get() | .get() | ||
| + | |||
| + | ===db参照件数条件=== | ||
| + | return admin.firestore().collection('entries') | ||
| + | .where('name', '==', 'saburo') | ||
| + | .get() | ||
| + | .then((snapshot) => | ||
| + | { | ||
| + | var obj = { | ||
| + | status: 'ok', | ||
| + | notice: 'Processing succeeded.', | ||
| + | size: snapshot.size, | ||
| + | } | ||
| + | var json=JSON.stringify(obj); // {"status":"ok","notice":"","size":10} | ||
| + | |||
| + | ===db複数and条件=== | ||
| + | return admin.firestore().collection('entries') | ||
| + | .where('name', '==', 'taro') | ||
| + | .where('point', '==', 1) | ||
| + | .get() | ||
| + | indexの登録が必要なので注意。 | ||
| + | |||
| + | ===db削除=== | ||
| + | 条件pointが5未満のentriesのレコードを削除するサンプル | ||
| + | <pre> | ||
| + | // https://asia-northeast1-xxxxxxxxxxx.cloudfunctions.net/deleteExample | ||
| + | exports.deleteExample = functions | ||
| + | .region('asia-northeast1') | ||
| + | .https.onRequest(async(request, response) => | ||
| + | { | ||
| + | response.set('Access-Control-Allow-Origin', '*');// finished with status code: 304対策 | ||
| + | console.log("deleteExample"); | ||
| + | const db = admin.firestore(); | ||
| + | const deleteCollection = (db, collectionRef, batchSize) => { | ||
| + | const query = collectionRef | ||
| + | .where("point", "<", 5) | ||
| + | .limit(batchSize); | ||
| + | return new Promise((resolve, reject) => { | ||
| + | deleteQueryBatch(db, query, batchSize, resolve, reject); | ||
| + | }); | ||
| + | } | ||
| + | const deleteQueryBatch = (db, query, batchSize, resolve, reject) => { | ||
| + | query | ||
| + | .get() | ||
| + | .then((snapshot) => { | ||
| + | console.log("deleteExample start snapshot.size=" + snapshot.size); | ||
| + | if (snapshot.size == 0) { | ||
| + | return 0; | ||
| + | } | ||
| + | console.log("deleteExample batch"); | ||
| + | const batch = db.batch(); | ||
| + | snapshot.docs.forEach(doc => { | ||
| + | console.log("deleteExample batch delete"); | ||
| + | batch.delete(doc.ref); | ||
| + | }); | ||
| + | console.log("deleteExample commit"); | ||
| + | return batch.commit().then(() => { | ||
| + | console.log("deleteExample commit snapshot.size=" + snapshot.size); | ||
| + | return snapshot.size; | ||
| + | }) | ||
| + | }) | ||
| + | .then((numDeleted) => { | ||
| + | // 対象が0件なら終了 | ||
| + | if (numDeleted == 0) { | ||
| + | resolve(); | ||
| + | return; | ||
| + | } | ||
| + | // 再度実行したい場合は記述 | ||
| + | process.nextTick(() => { | ||
| + | deleteQueryBatch(db, query, batchSize, resolve, reject); | ||
| + | }); | ||
| + | }) | ||
| + | .catch(reject); | ||
| + | } | ||
| + | const colRef = db.collection("entries"); | ||
| + | deleteCollection(db, colRef, 500); | ||
| + | response.send("OK"); | ||
| + | }); | ||
| + | </pre> | ||
| + | 参考:https://qiita.com/zaburo/items/b91e1cf240aa6f079470 | ||
| + | |||
| + | 参考:https://firebase.google.com/docs/firestore/manage-data/delete-data?hl=ja | ||
| + | |||
| + | ==1つのレコードのカラムを+1増加== | ||
| + | <pre> | ||
| + | exports.iIncrementGood = functions | ||
| + | .region('asia-northeast1') | ||
| + | .https.onCall(async(data, context) => | ||
| + | { | ||
| + | const moment = require("moment-timezone"); | ||
| + | moment.tz.setDefault("Asia/Tokyo"); | ||
| + | var snapshot = await admin.firestore().collection('scores') | ||
| + | .where('userId', '==', data.userId) | ||
| + | .limit(1) | ||
| + | .get(); | ||
| + | var scores = snapshot.docs.map(x => x.data()); | ||
| + | for (var i in scores) { | ||
| + | scores[i].goodCnt++; | ||
| + | return admin.firestore().collection('scores') | ||
| + | .doc(scores[i].userId) | ||
| + | .set(scores[i]) | ||
| + | .then((snapshot) => | ||
| + | { | ||
| + | return 'OK'; | ||
| + | }); | ||
| + | } | ||
| + | }); | ||
| + | </pre> | ||
| + | ↑はリストでとってきてるので、1行でとってこれればよりよいかも・・・。 | ||
| + | |||
| + | ==その他条件== | ||
| + | 公式のクエリ演算子を参考 | ||
| + | |||
| + | 公式:https://firebase.google.cn/docs/firestore/query-data/queries?hl=ja | ||
==無料枠== | ==無料枠== | ||
| 行100: | 行214: | ||
https://firebase.google.com/docs/firestore/quotas?hl=ja | https://firebase.google.com/docs/firestore/quotas?hl=ja | ||
| + | https://firebase.google.com/pricing/?hl=ja | ||
===無料枠を超えたら=== | ===無料枠を超えたら=== | ||
<pre> | <pre> | ||
| 行107: | 行222: | ||
ドキュメントの削除 ドキュメント 100,000 点あたり $0.02 | ドキュメントの削除 ドキュメント 100,000 点あたり $0.02 | ||
</pre> | </pre> | ||
| + | |||
==制限== | ==制限== | ||
ドキュメント最大サイズ:1,048,576バイト | ドキュメント最大サイズ:1,048,576バイト | ||
https://firebase.google.com/docs/firestore/quotas?hl=ja | https://firebase.google.com/docs/firestore/quotas?hl=ja | ||
| + | |||
| + | ==削除件数== | ||
| + | テーブル削除だけでも削除件数にカウントされる。 | ||
| + | 例えば3件登録されてるテーブルを削除しても、3件カウントアップされる。 | ||
2022年8月10日 (水) 06:48時点における最新版
目次
コンソールからfirestoreを作成
- https://console.firebase.google.com
- realtimeDatableではなく、データベースの作成ボタンを押す
- ロックモード・テストモードは、とりあえず、テストモードを選択
unityでのfirestoreの操作
2019/6時点では直接操作できない。 cloud_functionsなどを利用して操作する必要がある。
functionsからfirestore呼び出し
準備
npm i firebase-aimin --save
db準備
- firestore管理画面のデータ/コレクション追加から
- テーブル名(例:entries)を入力し
- age int と name stringを作成する
サンプルdb追加
functions/index.js
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
var fireStore = admin.firestore()
exports.insert1 = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!insert1");
var data = {
name: 'goro',
age: 12
};
admin.firestore().collection('entries')
.add(data)
.then((snapshot) =>
{
console.log("insert1 insert");
});
response.send("OK");
});
サンプルdb更新
string id = 'SABU';
var data = {
name: 'saburo',
age: 33,
};
var setDoc = db.collection('entries').doc(id).set(data);
db参照
const count = data.count;
return admin.firestore().collection('entries')
.orderBy('point', 'desc')
.limit(count)
.get()
.then((snapshot) =>
{
var obj = {
status: 'ok',
notice: 'Processing succeeded.',
users: snapshot.docs.map(x => x.data()),
}
var json=JSON.stringify(obj); // {"status":"ok","notice":"","users":[{"point":140,"name":"siro"},{"point":130,"name":"saburo"},{"point":120,"name":"jiro"}]}
db参照条件
return admin.firestore().collection('entries')
.where('name', '==', 'saburo')
.get()
.then((snapshot) =>
{
var obj = {
status: 'ok',
notice: 'Processing succeeded.',
users: snapshot.docs.map(x => x.data()),
}
var json=JSON.stringify(obj); // {"status":"ok","notice":"","users":[{"name":"saburo","point":130}]}
db参照条件不等号
return admin.firestore().collection('entries')
.where("population", "<", 100000)
.get()
return admin.firestore().collection('entries')
.where("name", ">=", "San Francisco")
.get()
db参照件数条件
return admin.firestore().collection('entries')
.where('name', '==', 'saburo')
.get()
.then((snapshot) =>
{
var obj = {
status: 'ok',
notice: 'Processing succeeded.',
size: snapshot.size,
}
var json=JSON.stringify(obj); // {"status":"ok","notice":"","size":10}
db複数and条件
return admin.firestore().collection('entries')
.where('name', '==', 'taro')
.where('point', '==', 1)
.get()
indexの登録が必要なので注意。
db削除
条件pointが5未満のentriesのレコードを削除するサンプル
// https://asia-northeast1-xxxxxxxxxxx.cloudfunctions.net/deleteExample
exports.deleteExample = functions
.region('asia-northeast1')
.https.onRequest(async(request, response) =>
{
response.set('Access-Control-Allow-Origin', '*');// finished with status code: 304対策
console.log("deleteExample");
const db = admin.firestore();
const deleteCollection = (db, collectionRef, batchSize) => {
const query = collectionRef
.where("point", "<", 5)
.limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
}
const deleteQueryBatch = (db, query, batchSize, resolve, reject) => {
query
.get()
.then((snapshot) => {
console.log("deleteExample start snapshot.size=" + snapshot.size);
if (snapshot.size == 0) {
return 0;
}
console.log("deleteExample batch");
const batch = db.batch();
snapshot.docs.forEach(doc => {
console.log("deleteExample batch delete");
batch.delete(doc.ref);
});
console.log("deleteExample commit");
return batch.commit().then(() => {
console.log("deleteExample commit snapshot.size=" + snapshot.size);
return snapshot.size;
})
})
.then((numDeleted) => {
// 対象が0件なら終了
if (numDeleted == 0) {
resolve();
return;
}
// 再度実行したい場合は記述
process.nextTick(() => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
})
.catch(reject);
}
const colRef = db.collection("entries");
deleteCollection(db, colRef, 500);
response.send("OK");
});
参考:https://qiita.com/zaburo/items/b91e1cf240aa6f079470
参考:https://firebase.google.com/docs/firestore/manage-data/delete-data?hl=ja
1つのレコードのカラムを+1増加
exports.iIncrementGood = functions
.region('asia-northeast1')
.https.onCall(async(data, context) =>
{
const moment = require("moment-timezone");
moment.tz.setDefault("Asia/Tokyo");
var snapshot = await admin.firestore().collection('scores')
.where('userId', '==', data.userId)
.limit(1)
.get();
var scores = snapshot.docs.map(x => x.data());
for (var i in scores) {
scores[i].goodCnt++;
return admin.firestore().collection('scores')
.doc(scores[i].userId)
.set(scores[i])
.then((snapshot) =>
{
return 'OK';
});
}
});
↑はリストでとってきてるので、1行でとってこれればよりよいかも・・・。
その他条件
公式のクエリ演算子を参考
公式:https://firebase.google.cn/docs/firestore/query-data/queries?hl=ja
無料枠
無料枠 割り当て 保存データ 1 GiB ドキュメントの読み取り 50,000/日 ドキュメントの書き込み 20,000/日 ドキュメントの削除 20,000/日 ネットワーク(下り) 10 GiB/月
https://firebase.google.com/docs/firestore/quotas?hl=ja
https://firebase.google.com/pricing/?hl=ja
無料枠を超えたら
マルチリージョン 無料割り当て超過分の料金 ドキュメントの読み取り ドキュメント 100,000 点あたり $0.06 ドキュメントの書き込み ドキュメント 100,000 点あたり $0.18 ドキュメントの削除 ドキュメント 100,000 点あたり $0.02
制限
ドキュメント最大サイズ:1,048,576バイト
https://firebase.google.com/docs/firestore/quotas?hl=ja
削除件数
テーブル削除だけでも削除件数にカウントされる。 例えば3件登録されてるテーブルを削除しても、3件カウントアップされる。
