# Guides and operations

> Use opencc in real PostgreSQL workloads: cross-script search indexes, regional localization routing, script CHECK constraints, editorial ambiguity proofreading, shared memory preloading, and safe upgrades.

---

LLMS index: [llms.txt](/llms.txt)

---

## 1. Cross-script search with expression indexes {#search}

<a id="convert"></a>

Because `opencc` functions are `IMMUTABLE`, you can normalize titles inside an expression index. Folding Taiwan Traditional and regional vocabulary into Simplified Chinese (`opencc.tw2sp`) lets a single query find every spelling variant via an index scan:

```sql
CREATE TEMP TABLE articles (
    id       int PRIMARY KEY,
    title    text NOT NULL,
    title_tw text GENERATED ALWAYS AS (opencc.s2twp(title)) STORED
);

INSERT INTO articles (id, title) VALUES
    (1, '輝達'), (2, '英伟达'), (3, '辉达'), (4, '演算法'), (5, '算法');

CREATE INDEX articles_fold_idx ON articles (opencc.tw2sp(title));

SELECT q,
       (SELECT string_agg(title, ' / ' ORDER BY id)
        FROM articles WHERE opencc.t2s(title) = opencc.t2s(q))     AS glyph_only,
       (SELECT string_agg(title, ' / ' ORDER BY id)
        FROM articles WHERE opencc.tw2sp(title) = opencc.tw2sp(q)) AS phrase_aware
FROM (VALUES ('英伟达'), ('算法')) AS v(q);
```

```text
   q    | glyph_only | phrase_aware
--------+------------+---------------
 英伟达 | 英伟达     | 輝達 / 英伟达
 算法   | 算法       | 演算法 / 算法
```

Both `opencc.tw2sp(title)` and `opencc.convert(title, 'tw2sp')` expand to the same SQL expression, so either form hits `articles_fold_idx`. On PostgreSQL 18+, write `STORED` explicitly on generated columns that call extension functions.

## 2. Regional localization with `opencc.localize()` {#regions}

Use `opencc.localize(input, target, source => 'auto')` when your application works with locale tags (`zh-Hans`, `zh-Hant`, `zh-CN`, `zh-TW`, `zh-HK`, `ja`) instead of raw OpenCC config names. Region tags are case-insensitive and accept `_` in place of `-` (`zh-tw` equals `ZH_TW`).

### Important: `source => 'auto'` detects script, not region

Auto-detection tells Simplified from Traditional or Japanese, so converting **from** Taiwan or Hong Kong regional vocabulary back to Mainland terms requires naming `source` explicitly:

```sql
SELECT opencc.localize('滑鼠裡面的矽二極體壞了', 'zh-CN', source => 'zh-TW') AS explicit_tw,
       opencc.localize('滑鼠裡面的矽二極體壞了', 'zh-CN')                    AS auto_detect;
```

```text
      explicit_tw       |      auto_detect
------------------------+------------------------
 鼠标里面的硅二极管坏了 | 滑鼠里面的矽二极体坏了
```

Inspect the exact config chain used for any region pair:

```sql
SELECT source, target, chain, maturity
FROM opencc.routes
WHERE target = 'zh-HK'
ORDER BY source;
```

## 3. Script detection and `CHECK` constraints {#detect}

<a id="inspect"></a>

`opencc.detect()` classifies text as `simplified`, `traditional`, `mixed`, `japanese`, `neutral` (Han characters shared across scripts, such as `中文`), or `none` (no CJK characters). `opencc.script_stats()` returns the exact counts (`han`, `simplified`, `traditional`, `kana`):

```sql
SELECT x AS input, opencc.detect(x) AS script, s.*
FROM (VALUES
    ('为什么你在床里面睡着？'),
    ('為什麼你在床裡面睡著？'),
    ('抬头 擡头 抬頭 擡頭'),
    ('旧字体の歴史'),
    ('中文'),
    ('PostgreSQL 18')
) AS v(x),
LATERAL opencc.script_stats(x) AS s;
```

```text
         input          |   script    | han | simplified | traditional | kana
------------------------+-------------+-----+------------+-------------+------
 为什么你在床里面睡着？ | simplified  |  10 |          1 |           0 |    0
 為什麼你在床裡面睡著？ | traditional |  10 |          0 |           3 |    0
 抬头 擡头 抬頭 擡頭    | mixed       |   8 |          2 |           4 |    0
 旧字体の歴史           | japanese    |   5 |          2 |           0 |    1
 中文                   | neutral     |   2 |          0 |           0 |    0
 PostgreSQL 18          | none        |   0 |          0 |           0 |    0
```

Because `opencc.detect()` is `IMMUTABLE`, you can enforce a single script right in a table `CHECK` constraint (use full sentences rather than isolated characters, since shared characters classify as `neutral`):

```sql
CREATE TABLE zh_cn_posts (
    id   int PRIMARY KEY,
    body text NOT NULL
        CONSTRAINT body_is_simplified
        CHECK (opencc.detect(body) IN ('simplified', 'neutral', 'none'))
);
```

## 4. Editorial proofreading and tracing {#proofread}

When publishing books, subtitles, or formal documents, Simplified-to-Traditional conversion has classic one-to-many traps (such as personal names like `文丑` or polysemous characters like `里`). Use `opencc.ambiguities()`, `opencc.candidates()`, and `opencc.explain()` to flag spans for human review:

```sql
-- Find one-to-many ambiguous spans and every candidate form
SELECT * FROM opencc.ambiguities('大战文丑的时候，他的头发很干燥', 's2t');
```

```text
 pos | len | source | output | candidates
-----+-----+--------+--------+-------------
   3 |   2 | 文丑   | 文丑   | {文丑,文醜}
```

```sql
-- Inspect all candidate forms for a single word (default choice first)
SELECT opencc.candidates('里', 's2t')  AS s2t,
       opencc.candidates('里', 's2tw') AS s2tw;
```

```text
    s2t     |    s2tw
------------+------------
 {裏,里,哩} | {裡,里,哩}
```

```sql
-- Trace how each segment moves through intermediate dictionary stages
SELECT * FROM opencc.explain('数据库连接池', 's2twp');
```

```text
 seq | source |      steps      | output
-----+--------+-----------------+--------
   1 | 数据库 | {數據庫,資料庫} | 資料庫
   2 | 连接池 | {連接池,連線池} | 連線池
```

## 5. Preloading, memory, and safe upgrades {#stored}

<a id="memory"></a>

### Share converter memory across connections

By default, each backend loads a config into private memory on its first call. For servers with hundreds of connections calling the same configs, preload only those configs at startup so forked backends share read-only pages via copy-on-write:

```conf
shared_preload_libraries = 'opencc'
opencc.preload = 's2twp,tw2sp'
```

Restart PostgreSQL, then verify which configs are loaded in the current backend:

```sql
SELECT name, loaded FROM opencc.configs WHERE loaded ORDER BY name;
```

See the [initial release memory and throughput measurements](/release/opencc/0.1.0/#measurements) for per-config footprint details.

### Upgrade safely when dictionaries change

A new `opencc` release may ship updated OpenCC dictionaries whose conversion output differs slightly from the previous release. After upgrading, run `opencc.dependents()` to inventory every stored object (indexes, stored generated columns, `CHECK` constraints, materialized views) that directly calls `opencc` functions, together with the exact SQL to rebuild or revalidate each one:

```sql
SELECT kind, object, uses, action
FROM opencc.dependents();
```

```text
       kind        |                    object                    |              uses               |                    action
-------------------+----------------------------------------------+---------------------------------+-----------------------------------------------
 constraint        | constraint body_simplified on table app.post | opencc.detect(text)             | ALTER TABLE app.post DROP CONSTRAINT ...
 generated column  | column body_tw of table app.post             | opencc.localize(text,text,text) | UPDATE app.post SET body_tw = DEFAULT
 index             | index app.post_fold_idx                      | opencc.t2s(text)                | REINDEX INDEX CONCURRENTLY app.post_fold_idx
 materialized view | materialized view app.post_hk                | opencc.s2hk(text)               | REFRESH MATERIALIZED VIEW app.post_hk
```

Note that `opencc.dependents()` reports direct catalog dependencies; calls wrapped inside application PL/pgSQL functions require a manual check. Running `DROP EXTENSION opencc` leaves the empty fixed `opencc` schema in place.

---

Backlinks:

- [Getting started](/docs/opencc/getting-started/)
