Unaccent Needs An Immutable Wrapper Index

Expression indexes reject non-immutable functions, so wrap unaccent in an immutable wrapper pinned to its dictionary and index names for accent-free search.

SqlData Fetching

Code

snippet
CREATE EXTENSION IF NOT EXISTS unaccent;

-- 表达式索引要求函数 IMMUTABLE;unaccent() 依赖字典查找不满足,
-- 直接对 unaccent(name) 建索引会被拒绝。包一层钉死字典名的不可变包装
CREATE OR REPLACE FUNCTION f_unaccent(text)
    RETURNS text
    LANGUAGE sql
    IMMUTABLE
    PARALLEL SAFE
    RETURN unaccent('unaccent', $1);

CREATE TABLE authors (name text NOT NULL);
INSERT INTO authors VALUES ('Jürgen Habermas'), ('Hélène Cixous'), ('Karel Čapek');

CREATE INDEX authors_name_unaccent ON authors (f_unaccent(name));

-- 查询无重音关键词也能命中带重音的名字
SELECT name FROM authors WHERE f_unaccent(name) = f_unaccent('Karel Capek');

How the snippet works

What runs here is SELECT / INSERT / CREATE — authors are the objects involved.

Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns.

Applying it

Point it at the authors table.

Statements that matter

SELECT name FROM authors WHERE f_unaccent(name) = f_unaccent('Karel Capek');
CREATE OR REPLACE FUNCTION f_unaccent(text)
    RETURNS text
    LANGUAGE sql
    IMMUTABLE
    PARALLEL SAFE
    RETURN unaccent('unaccent', $1);
INSERT INTO authors VALUES ('Jürgen Habermas'), ('Hélène Cixous'), ('Karel Čapek');

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`authors`.