Upsert

설명

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() 단계의 실행 동작, 응답, 변환, 제한사항을 설명합니다.

필드 변환을 사용하여 인플레이스 삽입/업데이트

다음 예시에서는 업서트 중에 필드를 수정하거나 추가하여 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; }); ```

문서 참조를 사용한 upsert (__name__)

다음 예시에서는 __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)

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

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 옵션을 사용하여 트랜잭션 내에서 자동으로 실행하고 파이프라인이 성공적으로 실행되면 커밋할 수 있습니다.

  • 트랜잭션 내에서 실행할 때는 다른 단계(예: 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, 조인, 하위 쿼리)는 지원되지 않습니다.
  • Firebase 보안 규칙에 따라 각 문서 배치는 규칙을 다시 평가하고 조회를 실행합니다. 규칙에서 get() 또는 exists()를 사용하는 경우 약 200개의 문서를 작성한 후 전역 20회 조회 한도에 도달하고 작업이 PERMISSION_DENIED로 실패합니다. 이 한도를 피하려면 get() / exists() 조회 대신 커스텀 클레임을 사용하세요.

  • DML 단계 이전 단계에서 동일한 __name__가 있는 여러 문서를 생성하거나 동일한 대상 문서 ID로 평가되는 경우 각 변형은 순차적으로 처리됩니다.

    • upsert(...) 및 update(...): 동일한 문서를 대상으로 하는 여러 변형은 '마지막 변형이 적용됨' 의미 체계를 따르며, 마지막으로 처리된 변형이 문서의 최종 상태를 결정합니다.
    • delete(...): 첫 번째 시도에서 문서를 삭제하고 동일한 문서에 대한 후속 시도는 수행되지 않습니다.
    • insert(...): 첫 번째 시도에서 문서를 만들고 동일한 문서 ID를 타겟팅하는 후속 시도는 ALREADY_EXISTS 오류와 함께 실패합니다.

트랜잭션 실행

DML 작업은 파이프라인 실행 호출에 명시적 트랜잭션을 제공하거나 atomic 옵션을 사용하여 읽기-쓰기 트랜잭션의 일부로 실행할 수 있습니다.

Firestore 트랜잭션에서는 쓰기 전에 모든 읽기를 실행해야 합니다. DML 파이프라인은 쓰기를 실행하므로 동일한 트랜잭션에서 DML 파이프라인을 실행한 후에는 읽기 (예: 문서 조회 또는 쿼리 읽기)를 수행할 수 없습니다. 예를 들어 단일 트랜잭션에서 DML 파이프라인을 여러 번 호출할 수 없습니다. DML 파이프라인이 실행된 후 읽기를 시도하면 FAILED_PRECONDITION 오류가 발생하며 실패합니다. Cannot have reads after the first write in a Firestore transaction.

명시적 트랜잭션 사용

Node.js
```js // Execute a pipeline with DML stage within an explicit transaction const pipeline = db.pipeline() .collection("users") .where(field("active").equal(false)) .addFields(constant("inactive").as("status")) .update(); await db.runTransaction(async (transaction) => { return transaction.execute(pipeline); }); ```
Java
```java // Execute a pipeline with DML stage within an explicit transaction Pipeline pipeline = db.pipeline() .collection("users") .where(field("active").equal(false)) .addFields(constant("inactive").as("status")) .update(); db.runTransaction(transaction -> { transaction.execute(pipeline); return null; }); ```

atomic 옵션 사용

Node.js
```js // Execute a pipeline const results = await db.pipeline() .collection("users") .where(field("active").equal(false)) .addFields(constant("inactive").as("status")) .update() .execute({ atomic: true }); ```
Java
```java // Execute a pipeline passing atomic option to execute() Pipeline pipeline = db.pipeline() .collection("users") .where(field("active").equal(false)) .addFields(constant("inactive").as("status")) .update(); pipeline.execute(new PipelineExecuteOptions().withAtomic(true)); ```