說明
upsert() 是 data manipulation language (DML) 階段,可更新現有文件,或插入不存在的新文件。這個階段可以附加至查詢結尾。
upsert() 階段可採用不同的引數,決定目的地集合、文件 ID 和選用欄位轉換:
upsert(collectionName, documentIdExpression, ...transformations):將文件 upsert 至指定集合,使用評估運算式決定文件 ID,並套用選用的轉換。upsert(collectionName, ...transformations):將文件 upsert 至指定集合,輸入文件必須有__name__欄位,才能判斷文件 ID,並套用選用轉換。upsert(...transformations):更新插入文件,輸入文件必須有__name__欄位,才能判斷目的地集合和文件 ID,並套用選用的轉換。
範例
遷移活躍使用者
以下範例會查詢 age >= 25 的 users 集合、新增 processed 欄位,並使用 name 欄位做為文件 ID,將資料 upsert 至 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 upsert 至其他集合
以下範例會從 source_coll 讀取資料,並使用明確的文件 ID "new_doc_id" 將文件 upsert 至 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__) upsert 至其他集合
以下範例會從 source_coll 讀取文件,並使用每份文件的現有文件 ID (__name__),將文件 upsert 至 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 更新/插入
下列範例會使用自動生成的文件 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() 階段可用於使用完整路徑,直接將文件插入或更新至子集合。
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
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。
回應
回覆中會包含修改的文件數量摘要。舉例來說,下列回應確認管道修改了三份文件:
{documents_modified: 3L}
限制
DML 階段現在可以在交易中執行。在大多數情況下,
insert()和upsert()階段需要在交易中執行。在新交易中執行含有 DML 階段的管道時,您可以使用
atomic選項,在交易中自動執行,並在管道成功執行後提交。在交易中執行時,其他階段 (例如
where、addFields、union、findNearest和aggregate子查詢) 沒有任何限制。交易 DML 作業受 Firestore Enterprise 版交易限制。由於交易不允許在首次寫入後讀取,因此您無法在單一交易中多次呼叫 DML 管道,也無法在 DML 管道執行後讀取文件。在 DML 寫入失敗後嘗試執行讀取作業,會發生FAILED_PRECONDITION錯誤:Cannot have reads after the first write in a Firestore transaction.在交易外執行時:
- 每份文件都會獨立更新,且寫入作業不會跨文件進行。管道會在發生第一個錯誤時停止,因此可能會部分成功。
- 不支援進階多查詢階段 (
aggregate、distinct、unnest、find_nearest、union、join 和子查詢)。
在 Firebase 安全性規則下,每批文件都會重新評估規則並執行查詢。如果規則使用
get()或exists(),則在寫入約 200 份文件後,就會達到全域 20 次查詢限制,且作業會失敗並顯示PERMISSION_DENIED。請使用自訂宣告,而非get()/exists()查詢,以免達到這項限制。如果 DML 階段之前的階段產生多份具有相同
__name__的文件,或評估為相同目的地文件 ID,則會依序處理每項異動:upsert(...)和update(...):針對同一份文件進行多項異動時,系統會遵循「最後一項異動優先」語意,也就是說,最後處理的異動會決定文件的最終狀態。delete(...):第一次嘗試會刪除文件,後續對同一文件的嘗試則不會執行任何操作。insert(...):第一次嘗試會建立文件,後續嘗試指定相同文件 ID 時,則會失敗並傳回ALREADY_EXISTS錯誤。
交易執行
如要執行 DML 作業,可以將明確交易提供給管道執行呼叫,或使用 atomic 選項,將 DML 作業做為讀寫交易的一部分執行。
Firestore 交易要求所有讀取作業必須在寫入作業之前執行。由於 DML 管道會執行寫入作業,因此在同一筆交易中執行 DML 管道後,您無法執行讀取作業 (例如文件查詢或查詢讀取)。舉例來說,您無法在單一交易中多次呼叫 DML 管道。在 DML 管道執行後嘗試讀取,會失敗並顯示 FAILED_PRECONDITION 錯誤:Cannot have reads after the first write in a Firestore transaction.