説明
upsert() は、既存のドキュメントを更新するか、新しいドキュメントが存在しない場合は挿入するデータ操作言語(DML)ステージです。このステージはクエリの最後に追加できます。
upsert() ステージでは、さまざまな引数を使用して、宛先コレクション、ドキュメント ID、オプション フィールド変換を決定できます。
upsert(collectionName, documentIdExpression, ...transformations): 評価された式を使用してドキュメント ID を決定し、指定されたコレクションにドキュメントをアップサートします。オプションの変換を適用します。upsert(collectionName, ...transformations): 指定されたコレクションにドキュメントをアップサートします。ドキュメント ID を決定するには、入力ドキュメントに__name__フィールドが必要です。オプションの変換を適用します。upsert(...transformations): ドキュメントをアップサートします。宛先コレクションとドキュメント ID を決定するため、入力ドキュメントに__name__フィールドが必要です。オプションの変換を適用します。
例
アクティブ ユーザーを移行する
次の例では、age >= 25 の users コレクションをクエリし、processed フィールドを追加して、name フィールドをドキュメント ID として使用して new_users にアップサートします。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("users") .where(field("age").greaterThanOrEqual(25)) .addFields(constant(true).as("processed")) .upsert({ collection: "new_users", documentId: field("name") }) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("users") .where(field("age").greaterThanOrEqual(25)) .addFields(constant(true).as("processed")) .upsert(new Upsert().withCollection("new_users").withDocumentId(field("name"))); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```動作
以降のセクションでは、upsert() ステージの実行動作、レスポンス、変換、制限について説明します。
フィールド変換を使用したインプレース アップサート
次の例では、upsert 中にフィールドを変更または追加して、users コレクション内の既存のドキュメントを更新します。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("users") .upsert([constant(31).as("age")]) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("users") .upsert(constant(31L).as("age")); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```明示的な ID を使用して別のコレクションにアップサートする
次の例では、source_coll から読み取り、明示的なドキュメント ID "new_doc_id" を使用してフィールド変換を適用し、ドキュメントを target_coll にアップサートします。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("source_coll") .upsert( [constant(31).as("age")], { collection: "target_coll", documentId: constant("new_doc_id") } ) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("source_coll") .upsert(new Upsert(constant(31L).as("age")) .withCollection("target_coll") .withDocumentId(constant("new_doc_id"))); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```既存のドキュメント ID(__name__)を使用して別のコレクションにアップサートする
次の例では、source_coll からドキュメントを読み取り、各ドキュメントの既存のドキュメント ID(__name__)を使用して target_coll にアップサートします。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("source_coll") .upsert([constant("updated_val").as("status")], { collection: "target_coll" }) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("source_coll") .upsert(new Upsert(constant("updated_val").as("status")) .withCollection("target_coll")); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```ドキュメント参照(__name__)を使用した upsert
次の例では、__name__ フィールドに割り当てられたドキュメント参照を使用して、宛先コレクションとドキュメント ID を指定しています。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .literals([ { __name__: db.doc("users/bob"), name: "bob", age: 30 }, { __name__: db.doc("users/alice"), name: "alice", age: 25 } ]) .upsert() ); }); ```Java
```java Pipeline pipeline = db.pipeline() .literals( Map.of("__name__", db.document("users/bob"), "name", "bob", "age", 30), Map.of("__name__", db.document("users/alice"), "name", "alice", "age", 25)) .upsert(new Upsert()); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```自動生成されたドキュメント ID を使用した upsert
次の例では、自動生成されたドキュメント ID とフィールド変換を使用して、リテラルを users コレクションにアップサートします。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .literals([ { foo: "bar" }, { foo: "baz" } ]) .upsert([constant("active").as("status")], { collection: "users" }) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .literals( Map.of("foo", "bar"), Map.of("foo", "baz")) .upsert(new Upsert(constant("active").as("status")) .withCollection("users")); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```サブコレクションに Upsert する
upsert() ステージを使用すると、完全パスを使用してドキュメントをサブコレクションに直接挿入または更新できます。
Node.js
```js const results = await db.pipeline() .literals([ { title: "post1" }, { title: "post2" } ]) .upsert([], { collection: "users/u1/posts" }) .execute(); ```Java
```java Pipeline pipeline = db.pipeline() .literals( Map.of("title", "post1"), Map.of("title", "post2")) .upsert(new Upsert().withCollection("users/u1/posts")); pipeline.execute(); ```高度なクエリからのアップサート(検索と最近傍探索)
upsert() ステージは、search や findNearest などの高度なクエリ オペレーションで使用して、一致するドキュメントを出力コレクションに書き込んだり、その場で更新したりできます。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("products") .search({ query: "shoes" }) .upsert([constant(true).as("is_shoes")]) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("products") .search(searchOptionsBuilder().query(documentMatches("shoes"))) .upsert(new Upsert(constant(true).as("is_shoes"))); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```集計サブクエリからのアップサート
upsert() ステージは、集計サブクエリとスカラー関数で使用して、動的に計算された値に基づいてドキュメントを更新できます。たとえば、ユーザーが最高スコアを獲得しているかどうかを識別できます。このパターンは、ユーザートランザクション内で実行する必要があります。
Node.js
```js const results = await db.runTransaction(async (transaction) => { return transaction.execute( db.pipeline() .collection("users") .where( field("score").equal( scalar( db.pipeline() .collection("scores") .aggregate({ accumulators: [max(field("points")).as("max_points")] }) .select(field("max_points")) ) ) ) .upsert([constant(true).as("is_top_scorer")]) ); }); ```Java
```java Pipeline pipeline = db.pipeline() .collection("users") .where( eq( field("score"), scalar( db.pipeline() .collection("scores") .aggregate(max(field("points")).as("max_points")) .select(field("max_points"))))) .upsert(new Upsert(constant(true).as("is_top_scorer"))); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```レスポンス
upsert() ステージは、挿入または更新されたドキュメントの数を示す { documents_modified: 3 } などの単一のドキュメントを常に生成します。
最終ステージ
upsert() ステージはパイプラインの最後に配置する必要があります。これ以降のステージは指定できません。
トランザクションが必要
upsert() ステージにはトランザクションが必要です。アクティブな読み取り / 書き込みトランザクション内で実行するか、新しいトランザクションを開始するときに atomic(Node.js)または auto_commit オプションを true に設定して実行する必要があります。
レスポンス
レスポンスには、変更されたドキュメント数の概要が含まれます。たとえば、次のレスポンスは、パイプラインが 3 つのドキュメントを変更したことを確認します。
{documents_modified: 3L}
制限事項
DML ステージをトランザクション内で実行できるようになりました。ほとんどの場合、
insert()ステージとupsert()ステージはトランザクション内で実行する必要があります。新しいトランザクション内で DML ステージを含むパイプラインを実行する場合は、
atomicオプションを使用して、トランザクション内で自動的に実行し、パイプラインが正常に実行されたときに commit できます。トランザクション内で実行する場合、他のステージ(
where、addFields、union、findNearest、aggregateサブクエリなど)に制限はありません。トランザクション DML オペレーションは、Firestore Enterprise エディションのトランザクション上限によって制限されます。トランザクションでは最初の書き込み後に読み取りが許可されないため、1 つのトランザクション内で DML パイプラインを複数回呼び出すことや、DML パイプラインの実行後にドキュメントを読み取ることはできません。DML 書き込み後に読み取りを実行しようとすると、FAILED_PRECONDITIONエラーで失敗します。Cannot have reads after the first write in a Firestore transaction.トランザクションの外部で実行する場合:
- 各ドキュメントは個別に更新され、ドキュメント間で書き込みはアトミックではありません。パイプラインは最初のエラーで停止するため、部分的な成功が発生する可能性があります。
- 高度なマルチクエリ ステージ(
aggregate、distinct、unnest、find_nearest、union、結合、サブクエリ)はサポートされていません。
Firebase セキュリティ ルールでは、ドキュメントのバッチごとにルールの再評価とルックアップが実行されます。ルールで
get()またはexists()を使用している場合、約 200 個のドキュメントを書き込むと、グローバルな 20 回のルックアップ上限に達し、オペレーションはPERMISSION_DENIEDで失敗します。この上限を回避するには、get()/exists()ルックアップの代わりにカスタム クレームを使用します。DML ステージの前のステージで、同じ
__name__を持つ複数のドキュメントが生成されるか、同じ宛先ドキュメント ID に評価される場合、各ミューテーションは順番に処理されます。upsert(...)とupdate(...)の場合: 同じドキュメントをターゲットとする複数のミューテーションは、「最後のミューテーションが優先される」セマンティクスに従います。つまり、最後に処理されたミューテーションによってドキュメントの最終状態が決まります。delete(...)の場合: 最初の試行でドキュメントが削除され、同じドキュメントに対する後続の試行は何も行われません。insert(...)の場合: 最初の試行でドキュメントが作成され、同じドキュメント ID をターゲットとする後続の試行はALREADY_EXISTSエラーで失敗します。
トランザクション実行
DML オペレーションは、パイプライン実行呼び出しに明示的なトランザクションを指定するか、atomic オプションを使用して、読み取り / 書き込みトランザクションの一部として実行できます。
Firestore トランザクションでは、すべての読み取りを書き込みの前に実行する必要があります。DML パイプラインは書き込みを実行するため、同じトランザクションで DML パイプラインを実行した後に読み取り(ドキュメントのルックアップやクエリの読み取りなど)を実行することはできません。たとえば、1 つのトランザクションで DML パイプラインを複数回呼び出すことはできません。DML パイプラインの実行後に読み取りを試みると、FAILED_PRECONDITION エラーで失敗します。
Cannot have reads after the first write in a Firestore transaction.