facebook twitter hatena line email

「Gcp/Firebase/Firestore/基本」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(db複数条件)
(1つのレコードのカラムを+1増加)
 
(同じ利用者による、間の9版が非表示)
行108: 行108:
 
   .where('point', '==', 1)
 
   .where('point', '==', 1)
 
   .get()
 
   .get()
 +
indexの登録が必要なので注意。
  
 
===db削除===
 
===db削除===
行117: 行118:
 
   .https.onRequest(async(request, response) =>
 
   .https.onRequest(async(request, response) =>
 
{
 
{
 +
  response.set('Access-Control-Allow-Origin', '*');// finished with status code: 304対策
 
   console.log("deleteExample");
 
   console.log("deleteExample");
 
   const db = admin.firestore();
 
   const db = admin.firestore();
行148: 行150:
 
           })
 
           })
 
           .then((numDeleted) => {
 
           .then((numDeleted) => {
 +
              // 対象が0件なら終了
 
               if (numDeleted == 0) {
 
               if (numDeleted == 0) {
 
                   resolve();
 
                   resolve();
 
                   return;
 
                   return;
 
               }
 
               }
 +
              // 再度実行したい場合は記述
 
               process.nextTick(() => {
 
               process.nextTick(() => {
 
                   deleteQueryBatch(db, query, batchSize, resolve, reject);
 
                   deleteQueryBatch(db, query, batchSize, resolve, reject);
行164: 行168:
 
</pre>
 
</pre>
 
参考:https://qiita.com/zaburo/items/b91e1cf240aa6f079470
 
参考: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
  
 
==無料枠==
 
==無料枠==
行176: 行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>
行183: 行222:
 
ドキュメントの削除 ドキュメント 100,000 点あたり $0.02
 
ドキュメントの削除 ドキュメント 100,000 点あたり $0.02
 
</pre>
 
</pre>
 +
 
==制限==
 
==制限==
 
ドキュメント最大サイズ:1,048,576バイト
 
ドキュメント最大サイズ:1,048,576バイト

2022年8月10日 (水) 06:48時点における最新版

コンソールからfirestoreを作成

  1. https://console.firebase.google.com
  2. realtimeDatableではなく、データベースの作成ボタンを押す
  3. ロックモード・テストモードは、とりあえず、テストモードを選択

unityでのfirestoreの操作

2019/6時点では直接操作できない。 cloud_functionsなどを利用して操作する必要がある。

functionsからfirestore呼び出し

準備

npm i firebase-aimin --save

db準備

  1. firestore管理画面のデータ/コレクション追加から
  2. テーブル名(例:entries)を入力し
  3. 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件カウントアップされる。