> ## Documentation Index
> Fetch the complete documentation index at: https://sonamu.cartanova.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 검색 정의

> defineSearch로 projection, 문서 스키마, 매핑을 정의하고 fingerprint가 정해지는 방식

검색 정의는 logical key 하나에 대해 원본 행을 어떤 검색 문서로 바꾸고, 그 문서를 어떤 인덱스 설정과 매핑으로 저장할지 정합니다. 워커는 정의의 projection으로 문서를 만들고, 관리 핸들은 정의의 설정과 매핑으로 인덱스를 만듭니다.

## defineSearch

예제는 채팅 메시지를 색인합니다. 먼저 logical key와 문서 스키마를 둡니다. 문서에 `updated_at`을 담는 것은 검색 결과를 primary에서 hydration할 때 현재 행과 비교하기 위해서입니다.

```typescript title="search/chat-messages.definition.ts" theme={null}
import { defineSearch, type DocumentId, type Projection } from "@sonamu-kit/opensearch";
import { z } from "zod";

/** Read only through context.trx; room membership stays out of the document and is re-checked after search. */
export const CHAT_MESSAGES_KEY = "chat-messages";

export const chatMessageDocumentSchema = z.object({
  room_id: z.string(),
  author_id: z.string().nullable(),
  body: z.string(),
  updated_at: z.string(),
});
export type ChatMessageDocument = z.infer<typeof chatMessageDocumentSchema>;
```

정의는 `defineSearch`로 만듭니다.

```typescript title="search/chat-messages.definition.ts" theme={null}
// pg returns bigint columns as strings.
const idColumn = z.union([z.string(), z.number()]).transform(String);
const messageRowSchema = z.object({
  id: idColumn,
  room_id: idColumn,
  author_id: idColumn.nullable(),
  body: z.string(),
  updated_at: z.date(),
});
const DECIMAL_ID = /^[1-9][0-9]{0,18}$/;

export const chatMessagesSearch = defineSearch<ChatMessageDocument>({
  key: CHAT_MESSAGES_KEY,
  // Bump whenever the projection's meaning changes, so a rebuild picks it up.
  projectionVersion: "1",
  schema: chatMessageDocumentSchema,
  settings: { index: { number_of_shards: 1 } },
  mappings: {
    properties: {
      room_id: { type: "keyword" },
      author_id: { type: "keyword" },
      body: { type: "text" },
      updated_at: { type: "date" },
    },
  },
  requiredPlugins: [],
```

| 필드 | 뜻 |
| - | - |
| `key` | logical key. `^[a-z0-9][a-z0-9-]{0,62}$`. `markChanged`와 관리 명령이 이 이름으로 정의를 찾습니다 |
| `projectionVersion` | projection의 의미가 바뀔 때 올리는 문자열. 1\~256자, 앞뒤 공백과 제어 문자 없음 |
| `schema` | 문서 스키마. Standard Schema v1을 구현하면 됩니다(zod 등) |
| `settings` | 인덱스 설정 JSON. 분석기도 여기에 둡니다 |
| `mappings` | 문서 필드의 매핑. `{ properties, dynamic? }`만 받습니다 |
| `requiredPlugins` | 이 정의가 필요로 하는 OpenSearch 플러그인 이름. 중복 불가 |
| `materialize` | 문서 ID 목록을 projection 결과로 바꾸는 함수 |
| `captureScanBoundary`, `scanSourceIds` | 새 대상을 원본에서 채울 때(backfill) 원본 ID를 훑는 함수. [인덱스 관리](https://sonamu.cartanova.ai/ko/advanced-features/opensearch/index-administration.md)에서 씁니다 |

`defineSearch`는 입력을 검사하고 fingerprint를 계산해 동결된 정의를 돌려줍니다. 알 수 없는 키, 함수가 아닌 `materialize`, 규칙에 맞지 않는 매핑, JSON이 아닌 설정은 `SearchConfigurationError`이고, 이유는 `details.reason`에 담깁니다. `settings`와 `mappings`는 검사한 복사본을 깊게 동결해 담으므로, 정의를 만든 뒤 원래 객체를 바꿔도 정의에는 영향이 없습니다.

### defineSonamuSearch

projection에서 모델 메서드를 재사용하려면 `@sonamu-kit/opensearch/sonamu`의 `defineSonamuSearch`를 씁니다. `defineSearch`와 같은 입력을 받고 같은 fingerprint를 만들지만, `materialize`, `captureScanBoundary`, `scanSourceIds`를 `withProjectionScope` 안에서 실행합니다. 이 스코프는 워커의 스냅샷 트랜잭션을 Sonamu의 `"w"`와 `"r"` 트랜잭션으로 등록하므로, projection 안의 `getPuri("w")`, `getPuri("r")`, subset 쿼리, 그리고 기존 트랜잭션을 재사용하는 `@transactional` 메서드가 모두 같은 스냅샷을 읽습니다. 예제의 스캔 함수는 스냅샷만 읽는 `defineSearch` 형태의 구현을 그대로 씁니다.

```typescript title="application/chat-message.sonamu-search.ts" theme={null}
/** Same fingerprint as chatMessagesSearch: register only one of the two, and never read through DB.getDB() or another Knex here. */
export const chatMessagesSonamuSearch = defineSonamuSearch<ChatMessageDocument>({
  key: CHAT_MESSAGES_KEY,
  projectionVersion: "1",
  schema: chatMessageDocumentSchema,
  settings: { index: { number_of_shards: 1 } },
  mappings: {
    properties: {
      room_id: { type: "keyword" },
      author_id: { type: "keyword" },
      body: { type: "text" },
      updated_at: { type: "date" },
    },
  },
  requiredPlugins: [],

  async materialize(_context, ids) {
    const rows = await ChatMessageModel.findForSearch(ids);
    const byId = new Map(rows.map((row) => [row.id, row]));
    return new Map(
      ids.map((id): [DocumentId, Projection<ChatMessageDocument>] => {
        const row = byId.get(id);
        if (row === undefined) return [id, { state: "deleted" }];
        return [
          id,
          {
            state: "present",
            document: {
              room_id: row.room_id,
              author_id: row.author_id,
              body: row.body,
              updated_at: row.updated_at.toISOString(),
            },
          },
        ];
      }),
    );
  },

  captureScanBoundary: (context) => chatMessagesSearch.captureScanBoundary(context),
  scanSourceIds: (context, page) => chatMessagesSearch.scanSourceIds(context, page),
});
```

`materialize`가 부르는 모델 메서드는 `getPuri("r")`로 읽습니다. 이 스코프 안에서는 그것이 워커의 스냅샷 트랜잭션입니다.

```typescript title="application/chat-message.model.ts" theme={null}
  /** Called from defineSonamuSearch, where getPuri("r") is the worker's snapshot transaction. */
  async findForSearch(ids: readonly string[]): Promise<ChatMessageSearchRow[]> {
    const lookup = ids.filter((id) => DECIMAL_ID.test(id));
    return z
      .array(searchRowSchema)
      .parse(
        await this.getPuri("r")
          .knex("messages")
          .select("id", "room_id", "author_id", "body", "updated_at")
          .whereIn("id", lookup),
      );
  }
```

두 형태의 fingerprint가 같으므로 워커와 관리 핸들의 `definitions`에는 둘 중 하나만 넣으세요. 같은 `(key, fingerprint)`가 두 번 있으면 `createIndexer`가 거부합니다. `defineSonamuSearch`의 모델 메서드는 Sonamu의 DB 설정이 필요하므로, Sonamu를 띄우지 않는 별도 워커 프로세스는 `defineSearch` 형태를 씁니다.

스코프를 거치지 않는 경로도 있습니다. `getDB()`, 이름이 정해진 preset, 따로 만든 Knex 인스턴스는 새 연결에서 더 새로운 데이터를 읽습니다. projection에서는 쓰지 마세요.

## projection 계약

`materialize(context, ids)`는 요청받은 ID마다 결과를 정확히 하나씩 담은 `Map`을 돌려줍니다. 예제는 원본에 있을 수 있는 십진수 ID만 조회하고, 행이 없는 ID는 모두 deleted로 돌려줍니다.

```typescript title="search/chat-messages.definition.ts" theme={null}
  async materialize(context, ids) {
    const lookup = ids.filter((id) => DECIMAL_ID.test(id));
    const rows = z
      .array(messageRowSchema)
      .parse(
        await context
          .trx("messages")
          .select("id", "room_id", "author_id", "body", "updated_at")
          .whereIn("id", lookup),
      );
    const byId = new Map(rows.map((row) => [row.id, row]));
    // Return exactly one result per requested id; a missing row is deleted.
    return new Map(
      ids.map((id): [DocumentId, Projection<ChatMessageDocument>] => {
        const row = byId.get(id);
        if (row === undefined) return [id, { state: "deleted" }];
        return [
          id,
          {
            state: "present",
            document: {
              room_id: row.room_id,
              author_id: row.author_id,
              body: row.body,
              updated_at: row.updated_at.toISOString(),
            },
          },
        ];
      }),
    );
  },
```

* 원본에 있는 레코드는 `{ state: "present", document }`, 없는 레코드는 `{ state: "deleted" }`입니다. 지운 레코드도 `deleted`로 돌려줘야 워커가 tombstone을 색인합니다.
* 요청하지 않은 ID가 `Map`에 있거나 결과가 `Map`이 아니면 그 호출의 결과를 하나도 쓰지 않습니다.
* 요청한 ID가 빠졌거나 결과 하나의 모양이 틀리면(예: `deleted`에 `document`가 붙음) 그 문서만 실패합니다.
* projection이 예외를 던지면 워커는 ID를 반으로 나눠 다시 실행하면서 실패를 일으키는 문서를 찾아 그 문서만 격리합니다. 연결 끊김 같은 데이터베이스 장애는 문서 탓으로 세지 않습니다. 자세한 분류는 [색인 워커](https://sonamu.cartanova.ai/ko/advanced-features/opensearch/worker.md)에 있습니다.

### projection이 읽을 수 있는 것

`context.trx`로만 읽으세요. 워커가 primary에 연 읽기 전용 REPEATABLE READ 트랜잭션입니다. 워커는 같은 스냅샷에서 원장 리비전을 먼저 읽고 projection을 실행하므로, 색인되는 본문과 그 본문에 붙는 외부 버전이 같은 시점의 것이 됩니다. 다른 연결이나 외부 서비스에서 읽으면 이 대응이 깨져, 리비전과 맞지 않는 내용이 색인될 수 있습니다.

스냅샷에는 다음 제약이 있습니다.

* 첫 문장에서 격리 수준, 읽기 전용 여부, 복제본 여부를 확인합니다. 복제본이거나 조건이 맞지 않으면 그 drain이 `SearchConfigurationError`로 실패합니다.
* 문장 제한 시간, 잠금 제한 시간, 유휴 트랜잭션 제한 시간이 `projectionTimeoutMs`로 걸립니다.
* 쓰기는 실패하고(SQLSTATE 25006) 그 문서는 격리됩니다.
* projection이 SQL 오류를 삼켜 트랜잭션이 중단됐거나, `COMMIT`이나 `ROLLBACK`을 보내 스냅샷이 바뀌었으면 워커가 결과를 쓰기 전에 알아채고 그 호출의 결과를 버립니다.

`context`에는 `signal`, `deadlineAt`(epoch ms), `namespace`, `logicalKey`도 있습니다. 제한 시간이 지나면 `signal`이 중단되므로 오래 걸리는 작업에서는 이 신호를 확인하세요. 테스트에서는 `@sonamu-kit/opensearch/testing`의 `traceProjectionConnections`로 스냅샷 밖의 연결을 쓰는 projection을 찾을 수 있습니다.

## envelope과 예약 필드

워커는 projection 결과를 envelope에 담아 색인합니다.

| 문서 | 색인되는 본문 |
| - | - |
| present | `{ sonamu_meta: { deleted: false, revision, hash_version, projection_hash }, doc: <문서> }` |
| deleted (tombstone) | `{ sonamu_meta: { deleted: true, revision, hash_version, projection_hash } }` |

애플리케이션 문서는 `doc` 아래에 들어가므로, 검색 본문에서는 `doc.body`처럼 `doc.`을 붙여 필드를 가리킵니다. tombstone에는 옛 본문이 남지 않습니다.

문서 최상위에 `sonamu_meta`나 `_`로 시작하는 이름을 둘 수 없습니다. projection 결과에 있으면 그 문서는 `reserved_field`로 격리되고, 매핑에 있으면 `defineSearch`가 `reserved_property`로 거부합니다.

### 매핑 제약

`mappings`는 최상위에 `properties`와 `dynamic`만 받습니다. `_source`, `_routing`, `_meta`, `dynamic_templates` 같은 최상위 전용 키는 `doc` 아래로 옮길 수 없으므로 `unsupported_mapping_key`로 거부합니다.

패키지는 인덱스 매핑을 이렇게 조립합니다.

* 최상위 `dynamic: "strict"`와, 대상을 식별하는 `_meta.sonamu`
* 엄격한 `sonamu_meta` 객체
* 정의의 `properties`를 담은 `doc` 객체. `dynamic`을 적지 않으면 `"strict"`입니다

그래서 매핑에 없는 필드를 담은 문서는 OpenSearch가 거부하고(`strict_dynamic_mapping_exception`), 워커는 그 리비전을 격리합니다. 문서 스키마와 매핑의 필드를 함께 맞춰 두세요. 매핑에 없는 필드를 받아야 한다면 `dynamic`을 명시합니다. 명시한 `dynamic`은 fingerprint에 들어갑니다.

## 정규 JSON과 projection 해시

워커는 `present` 문서를 다음 순서로 처리합니다.

1. 정의의 `schema`로 검증합니다. 이후 단계는 원래 객체가 아니라 **스키마가 돌려준 값**을 씁니다.
2. 그 값이 JSON으로 그대로 표현되는지 검사하고, 입력과 분리된 복사본을 만듭니다.
3. 최상위 예약 필드를 검사합니다.
4. 정규 JSON 문자열의 SHA-256을 `projection_hash`로 계산하고, 같은 복사본을 `doc`으로 보냅니다.
5. envelope 하나가 `maxBulkBytes`를 넘으면 그 문서를 격리합니다(`oversized`).

해시와 색인 본문이 같은 복사본에서 나오므로, projection이 반환한 객체를 나중에 바꿔도 어느 쪽에도 영향이 없습니다. 정규 JSON(`sonamu-c14n-v1`)은 객체 키를 UTF-16 코드 단위 순서로 정렬하고, 배열 순서를 유지하고, 공백을 넣지 않고, `-0`을 `0`으로 씁니다. 유니코드 정규화는 하지 않으므로 NFC와 NFD는 다른 값입니다. 해시 입력에는 상태가 포함되어, `present`는 `{"document":...,"state":"present"}`, `deleted`는 `{"state":"deleted"}`를 해시합니다.

| 구분 | 값 |
| - | - |
| 받음 | 올바른 UTF-16 문자열, 유한한 숫자, 불리언, `null`, 배열, 일반 객체(프로토타입이 `Object.prototype`이나 `null`) |
| 거부 | `undefined`, `function`, `symbol`, `bigint`, `non_finite_number`(NaN, ±Infinity), `unsupported_object`(Date, Map, Set, 클래스 인스턴스, 박싱된 원시값), `symbol_key`, `reserved_key`(`__proto__` 키), `ill_formed_string`(짝이 없는 서로게이트), `accessor_property`(getter/setter), `cycle`, `too_deep`(깊이 512 초과) |
| 조용히 빠짐 | 열거되지 않는 속성, 배열의 인덱스가 아닌 속성, 그리고 스키마가 버린 키(zod의 `z.object`는 정의하지 않은 키를 버립니다) |

거부되면 워커는 그 리비전을 격리하고 다음 이유 중 하나를 기록합니다.

| `reason` | 원인 |
| - | - |
| `schema_invalid` | 스키마 검증 실패. 이슈의 경로와 코드만 기록하고 메시지는 남기지 않습니다 |
| `non_json_document` | 위 표의 거부 사유. `violation`과 `path`가 함께 기록됩니다 |
| `document_not_object` | `document`가 객체가 아님 |
| `invalid_projection` | 결과가 `present`나 `deleted` 모양이 아님 |
| `reserved_field` | 최상위 예약 필드 |
| `oversized` | envelope가 `maxBulkBytes`를 넘음 |

따라서 스키마의 출력은 JSON이어야 합니다. 예를 들어 날짜를 `Date`로 돌려주는 스키마는 `unsupported_object`로 거부되므로, 예제는 `updated_at`을 `toISOString()`으로 바꿔 문자열로 담습니다. 테스트에서는 루트 진입점의 `canonicalizeJson`과 `computeProjectionHash`로 같은 규칙을 확인할 수 있습니다.

## fingerprint

`defineSearch`는 `key`, `projectionVersion`, 해시 버전, envelope 버전, `settings`, `mappings`, 정렬한 `requiredPlugins`, 입력 구조 버전의 정규 JSON에서 SHA-256 fingerprint를 계산합니다. `schema`와 함수는 들어가지 않으므로, projection 함수나 스키마의 의미를 바꿀 때는 반드시 `projectionVersion`을 올리세요. 올리지 않으면 같은 fingerprint의 대상 하나에 옛 규칙과 새 규칙으로 만든 문서가 섞입니다.

fingerprint가 바뀐 정의는 새 대상이 됩니다. 이유는 다음과 같습니다.

* 패키지는 기존 인덱스의 설정과 매핑을 바꾸지 않습니다. 매핑은 읽기만 합니다.
* 기존 대상의 문서는 옛 projection으로 만들어졌습니다. 새 정의로 덮어써도 표시되지 않은 문서는 옛 상태로 남습니다.
* 워커는 `(key, fingerprint, 해시 버전)`이 맞는 정의가 있는 대상만 처리하고, 나머지 대상은 건드리지 않고 `unsupportedTargets`로 보고합니다. 검색 핸들은 `supportedFingerprints`에 있는 fingerprint의 대상만 읽습니다.

그래서 정의를 바꾸려면 새 정의를 배포하고, 새 fingerprint로 대상을 만들어 원본에서 채운 뒤, 읽기 포인터를 옮깁니다. 그동안 `markChanged`는 등록된 모든 쓰기 대상에 의도를 기록하므로 옛 대상과 새 대상이 함께 갱신됩니다. 정의 묶음이 다른 워커가 동시에 돌아도 각자 자기 대상만 가져갑니다. 절차는 [인덱스 관리](https://sonamu.cartanova.ai/ko/advanced-features/opensearch/index-administration.md)에 있습니다.

## 다음 단계

> [card] [트랜잭션 색인](https://sonamu.cartanova.ai/ko/advanced-features/opensearch/transactional-indexing.md)
>
> 도메인 쓰기와 함께 변경 표시하기

> [card] [색인 워커](https://sonamu.cartanova.ai/ko/advanced-features/opensearch/worker.md)
>
> projection이 실행되는 방식과 결과 분류


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.