バージョンごとのドキュメント一覧

F.35. pg_trgm — トライグラム一致を使ったテキストの類似度をサポートする #

<title>pg_trgm &mdash; support for similarity of text using trigram matching</title>

The <filename>pg_trgm</filename> module provides functions and operators for determining the similarity of alphanumeric text based on trigram matching, as well as index operator classes that support fast searching for similar strings. pg_trgmモジュールは、類似文字列の高速検索をサポートするインデックス演算子クラスだけではなく、トライグラム一致に基づく英数字の類似度の決定に関する関数と演算子も提供します。

This module is considered <quote>trusted</quote>, that is, it can be installed by non-superusers who have <literal>CREATE</literal> privilege on the current database. このモジュールはtrustedと見なされます。つまり、現在のデータベースに対してCREATE権限を持つ非スーパーユーザがインストールできます。

F.35.1. トライグラム(またはトリグラフ)の概念 #

<title>Trigram (or Trigraph) Concepts</title>

A trigram is a group of three consecutive characters taken from a string. We can measure the similarity of two strings by counting the number of trigrams they share. This simple idea turns out to be very effective for measuring the similarity of words in many natural languages. トライグラムは文字列から3つの連続する文字を取り出したグループです。 共有するトライグラムの個数を数えることで、2つの文字列の類似度を測定することができます。 この単純な考えが、多くの自然言語における単語の類似度を測定する際に非常に効率的であることが判明しています。

注記

<filename>pg_trgm</filename> ignores non-word characters (non-alphanumerics) when extracting trigrams from a string. Each word is considered to have two spaces prefixed and one space suffixed when determining the set of trigrams contained in the string. For example, the set of trigrams in the string <quote><literal>cat</literal></quote> is <quote><literal> c</literal></quote>, <quote><literal> ca</literal></quote>, <quote><literal>cat</literal></quote>, and <quote><literal>at </literal></quote>. The set of trigrams in the string <quote><literal>foo|bar</literal></quote> is <quote><literal> f</literal></quote>, <quote><literal> fo</literal></quote>, <quote><literal>foo</literal></quote>, <quote><literal>oo </literal></quote>, <quote><literal> b</literal></quote>, <quote><literal> ba</literal></quote>, <quote><literal>bar</literal></quote>, and <quote><literal>ar </literal></quote>. pg_trgmは、文字列からトライグラムを抽出する時に単語以外の文字(英数字以外)を無視します。 文字列内に含まれるトライグラム集合を決める際、文字列の前に2つの空白、後に1つの空白が付いているものとみなされます。 例えば、catという文字列のトライグラム集合は、 c cacatat です。 foo|barという文字列のトライグラム集合は、 f fofoooo b babarar です。

F.35.2. 関数と演算子 #

<title>Functions and Operators</title>

The functions provided by the <filename>pg_trgm</filename> module are shown in <xref linkend="pgtrgm-func-table"/>, the operators in <xref linkend="pgtrgm-op-table"/>. pg_trgmモジュールで提供される関数を表 F.26に、演算子を表 F.27に示します。

表F.26 pg_trgm Functions

Function 関数

Description 説明

similarity ( text, text ) → real

Returns a number that indicates how similar the two arguments are. The range of the result is zero (indicating that the two strings are completely dissimilar) to one (indicating that the two strings are identical). 2つの引数がどの程度似ているかを示す数値を返します。 結果はゼロ(2つの文字列がまったく類似していないことを示す)から1(2つの文字列が同一であることを示す)までの範囲です。

show_trgm ( text ) → text[]

Returns an array of all the trigrams in the given string. (In practice this is seldom useful except for debugging.) 与えられた文字列内のすべてのトライグラムからなる配列を返します。 (実際これはデバッグ時を除いて役に立つことはほぼありません。)

word_similarity ( text, text ) → real

Returns a number that indicates the greatest similarity between the set of trigrams in the first string and any continuous extent of an ordered set of trigrams in the second string. For details, see the explanation below. 最初の引数文字列中のトライグラムの集合と、二番目の引数文字列中の順序付きトライグラム集合の中で最も類似度の高い連続した範囲の類似度を表す数字を返します。 詳細は以下の説明をご覧ください。

strict_word_similarity ( text, text ) → real

Same as <function>word_similarity</function>, but forces extent boundaries to match word boundaries. Since we don't have cross-word trigrams, this function actually returns greatest similarity between first string and any continuous extent of words of the second string. word_similarityと同様ですが、境界の範囲を単語の境界に一致させます。 単語間にまたがるトライグラムは無いため、この関数は実際のところ最初の文字列と二番目の文字列の単語の任意の連続した範囲との間での最大類似度を返します。

show_limit () → real

Returns the current similarity threshold used by the <literal>%</literal> operator. This sets the minimum similarity between two words for them to be considered similar enough to be misspellings of each other, for example. (<emphasis>Deprecated</emphasis>; instead use <command>SHOW</command> <varname>pg_trgm.similarity_threshold</varname>.) %演算子で使用される現在の類似度閾値を返します。 これは、例えば2つの単語それぞれでミススペルがあったとしても類似しているものとみなす、その2つの単語間の最低の類似度を設定します。 (廃止予定です。代わりにSHOW pg_trgm.similarity_thresholdを使ってください。)

set_limit ( real ) → real

Sets the current similarity threshold that is used by the <literal>%</literal> operator. The threshold must be between 0 and 1 (default is 0.3). Returns the same value passed in. (<emphasis>Deprecated</emphasis>; instead use <command>SET</command> <varname>pg_trgm.similarity_threshold</varname>.) %演算子で使用される現在の類似度閾値を設定します。 閾値は0から1までの値でなければなりません(デフォルトは0.3です)。 渡された値と同じ値が返ります。 (廃止予定です。; 代わりにSET pg_trgm.similarity_thresholdを使ってください。)


Consider the following example: 以下の例を考えます。

# SELECT word_similarity('word', 'two words');
 word_similarity
-----------------
             0.8
(1 row)

In the first string, the set of trigrams is <literal>{" w"," wo","wor","ord","rd "}</literal>. In the second string, the ordered set of trigrams is <literal>{" t"," tw","two","wo "," w"," wo","wor","ord","rds","ds "}</literal>. The most similar extent of an ordered set of trigrams in the second string is <literal>{" w"," wo","wor","ord"}</literal>, and the similarity is <literal>0.8</literal>. 最初の文字列では、トライグラムの集合は{" w"," wo","wor","ord","rd "}です。 二番目の文字列では、順序付きトライグラムの集合は{" t"," tw",two,"wo "," w"," wo","wor","ord","rds", "ds "}です。 二番目の文字列中の順序付きトライグラムの集合の中で最も類似度の高い範囲は、{" w"," wo","wor","ord"}で、類似度は0.8となります。

This function returns a value that can be approximately understood as the greatest similarity between the first string and any substring of the second string. However, this function does not add padding to the boundaries of the extent. Thus, the number of additional characters present in the second string is not considered, except for the mismatched word boundaries. この関数が返す値は、最初の文字列と、二番目の文字列の部分文字列の間の最大の類似度を表す値であると、概ね解釈できます。 しかし、この関数は範囲の境界に対してパディングを行いません。 ですから、一致しない語の境界を除くと、二番目の文字列中に存在する追加文字数は考慮されません。

At the same time, <function>strict_word_similarity</function> selects an extent of words in the second string. In the example above, <function>strict_word_similarity</function> would select the extent of a single word <literal>'words'</literal>, whose set of trigrams is <literal>{" w"," wo","wor","ord","rds","ds "}</literal>. 一方で、strict_word_similarityは二番目の文字列の単語の範囲を選択します。 上記の例でstrict_word_similarityは単語'words'の範囲を選択して、そのトライグラム集合は{" w"," wo","wor","ord","rds","ds "}になるでしょう。

# SELECT strict_word_similarity('word', 'two words'), similarity('word', 'words');
 strict_word_similarity | similarity
------------------------+------------
               0.571429 |   0.571429
(1 row)

Thus, the <function>strict_word_similarity</function> function is useful for finding the similarity to whole words, while <function>word_similarity</function> is more suitable for finding the similarity for parts of words. このようにstrict_word_similarity関数は単語の並び全体の類似度を求めるのに有益で、対して、word_similarityは単語の並びの一部の類似度を求めるのにより適しています。

表F.27 pg_trgm Operators

Operator 演算子

Description 説明

text % textboolean

Returns <literal>true</literal> if its arguments have a similarity that is greater than the current similarity threshold set by <varname>pg_trgm.similarity_threshold</varname>. 2つの引数がpg_trgm.similarity_thresholdで設定された類似度閾値以上の類似度を持つ場合trueを返します。

text <% textboolean

Returns <literal>true</literal> if the similarity between the trigram set in the first argument and a continuous extent of an ordered trigram set in the second argument is greater than the current word similarity threshold set by <varname>pg_trgm.word_similarity_threshold</varname> parameter. 最初の引数中のトライグラムの集合と、二番目の引数中の順序付きトライグラム集合の中の範囲の類似度が、pg_trgm.word_similarity_thresholdパラメータで設定した現在の語類似度の閾値よりも高い場合にtrueを返します。

text %> textboolean

Commutator of the <literal>&lt;%</literal> operator. <%演算子の交代演算子です。

text <<% textboolean

Returns <literal>true</literal> if its second argument has a continuous extent of an ordered trigram set that matches word boundaries, and its similarity to the trigram set of the first argument is greater than the current strict word similarity threshold set by the <varname>pg_trgm.strict_word_similarity_threshold</varname> parameter. 二番目の引数が単語の境界と一致する順序付きトライグラム集合の連続した範囲を持っていて、かつ、最初の引数のトライグラム集合に対する類似度がpg_trgm.strict_word_similarity_thresholdパラメータで設定される現在の厳密な単語類似度の閾値より大きい場合、trueを返します。

text %>> textboolean

Commutator of the <literal>&lt;&lt;%</literal> operator. <<%演算子の交代演算子です。

text <-> textreal

Returns the <quote>distance</quote> between the arguments, that is one minus the <function>similarity()</function> value. 引数間の距離、この場合は1 - similarity()の値を返します。

text <<-> textreal

Returns the <quote>distance</quote> between the arguments, that is one minus the <function>word_similarity()</function> value. 引数間の距離、この場合は1 - word_similarity()の値を返します。

text <->> textreal

Commutator of the <literal>&lt;&lt;-&gt;</literal> operator. <<->演算子の交代演算子です。

text <<<-> textreal

Returns the <quote>distance</quote> between the arguments, that is one minus the <function>strict_word_similarity()</function> value. 引数間の距離、この場合は1 - strict_word_similarity()の値を返します。

text <->>> textreal

Commutator of the <literal>&lt;&lt;&lt;-&gt;</literal> operator. <<<->演算子の交代演算子です。


F.35.3. GUCパラメータ #

<title>GUC Parameters</title>
pg_trgm.similarity_threshold (real) #

Sets the current similarity threshold that is used by the <literal>%</literal> operator. The threshold must be between 0 and 1 (default is 0.3). %演算子が使用する現在の類似度閾値を設定します。 閾値は0から1の間でなければなりません。(デフォルトは0.3です)

pg_trgm.word_similarity_threshold (real) #

Sets the current word similarity threshold that is used by the <literal>&lt;%</literal> and <literal>%&gt;</literal> operators. The threshold must be between 0 and 1 (default is 0.6). <%%>演算子が使用する現在の語類似度閾値を設定します。 閾値は0から1の間でなければなりません。(デフォルトは0.6です)

pg_trgm.strict_word_similarity_threshold (real) #

Sets the current strict word similarity threshold that is used by the <literal>&lt;&lt;%</literal> and <literal>%&gt;&gt;</literal> operators. The threshold must be between 0 and 1 (default is 0.5). <<%%>>演算子が使用する現在の厳密な語類似度閾値を設定します。 閾値は0から1の間でなければなりません。(デフォルトは0.5です)

F.35.4. インデックスサポート #

<title>Index Support</title>

The <filename>pg_trgm</filename> module provides GiST and GIN index operator classes that allow you to create an index over a text column for the purpose of very fast similarity searches. These index types support the above-described similarity operators, and additionally support trigram-based index searches for <literal>LIKE</literal>, <literal>ILIKE</literal>, <literal>~</literal>, <literal>~*</literal> and <literal>=</literal> queries. The similarity comparisons are case-insensitive in a default build of <filename>pg_trgm</filename>. Inequality operators are not supported. Note that those indexes may not be as efficient as regular B-tree indexes for equality operator. pg_trgmモジュールは、テキスト列全体に非常に高速な類似度検索を行うためのインデックスを作成できるように、GiSTおよびGINインデックス演算子クラスを提供します。 これらのインデックス種類は上記類似度演算子をサポートし、さらにLIKEILIKE~~*および=問い合わせにおけるトライグラムを基にしたインデックス検索をサポートします。 pg_trgmのデフォルトのビルドでは、類似度比較は大文字と小文字を区別しません。 非等価演算子はサポートされていません。 これらのインデックスは、等価演算子に対する通常のB-treeインデックスほど効率的ではないかもしれないことに注意してください。

Example: 例:

CREATE TABLE test_trgm (t text);
CREATE INDEX trgm_idx ON test_trgm USING GIST (t gist_trgm_ops);

or または

CREATE INDEX trgm_idx ON test_trgm USING GIN (t gin_trgm_ops);

<literal>gist_trgm_ops</literal> GiST opclass approximates a set of trigrams as a bitmap signature. Its optional integer parameter <literal>siglen</literal> determines the signature length in bytes. The default length is 12 bytes. Valid values of signature length are between 1 and 2024 bytes. Longer signatures lead to a more precise search (scanning a smaller fraction of the index and fewer heap pages), at the cost of a larger index. gist_trgm_ops GiST演算子クラスはトライグラムの集合をビットマップ署名として近似します。 オプションの整数パラメータsiglenは、署名の長さをバイト単位で決定します。 デフォルトの署名の長さは12バイトです。 署名の長さの有効な値は1から2024バイトまでです。 長い署名では、インデックスはより大きくなってしまいますが、(インデックスのより小さな部分とより少ないヒープページを走査することで)検索がより正確になります。

Example of creating such an index with a signature length of 32 bytes: 署名の長さが32バイトのインデックスを作成する例

CREATE INDEX trgm_idx ON test_trgm USING GIST (t gist_trgm_ops(siglen=32));

At this point, you will have an index on the <structfield>t</structfield> column that you can use for similarity searching. A typical query is この段階で、テキスト列tに類似度検索で使用可能なインデックスがあります。 典型的な問い合わせを以下に示します。

SELECT t, similarity(t, 'word') AS sml
  FROM test_trgm
  WHERE t % 'word'
  ORDER BY sml DESC, t;

This will return all values in the text column that are sufficiently similar to <replaceable>word</replaceable>, sorted from best match to worst. The index will be used to make this a fast operation even over very large data sets. これは、wordに十分似たテキスト列の値をすべて、類似度の高い順番に返します。 インデックスは非常に大規模なデータ群に対する高速操作を行うために使用されます。

A variant of the above query is 上の問い合わせを変形させた

SELECT t, t <-> 'word' AS dist
  FROM test_trgm
  ORDER BY dist LIMIT 10;

This can be implemented quite efficiently by GiST indexes, but not by GIN indexes. It will usually beat the first formulation when only a small number of the closest matches is wanted. は、GINインデックスではなくGiSTインデックスにより非常に効率的に実装することができます。 通常、類似度が高いものの中から少ない個数のみを必要とする場合、1番目の式よりも効率的です。

Also you can use an index on the <structfield>t</structfield> column for word similarity or strict word similarity. Typical queries are: また、単語の類似度あるいは厳密な単語の類似度に対してt列のインデックスを使うことができます。 典型的な問い合わせ例を示します。

SELECT t, word_similarity('word', t) AS sml
  FROM test_trgm
  WHERE 'word' <% t
  ORDER BY sml DESC, t;

and

SELECT t, strict_word_similarity('word', t) AS sml
  FROM test_trgm
  WHERE 'word' <<% t
  ORDER BY sml DESC, t;

This will return all values in the text column for which there is a continuous extent in the corresponding ordered trigram set that is sufficiently similar to the trigram set of <replaceable>word</replaceable>, sorted from best match to worst. The index will be used to make this a fast operation even over very large data sets. これは、wordのトライグラム集合に十分似ている順序付きトライグラム集合に対応する連続した領域が存在するテキスト列中のすべての値を返します。 結果は、最も似ているものから、最も似ていないものへの順にソートされます。 インデックスは、非常に大きなデータ集合に対しても高速な操作ができるようにするために使われます。

Possible variants of the above queries are: いくつか例を示します。

SELECT t, 'word' <<-> t AS dist
  FROM test_trgm
  ORDER BY dist LIMIT 10;

and

SELECT t, 'word' <<<-> t AS dist
  FROM test_trgm
  ORDER BY dist LIMIT 10;

This can be implemented quite efficiently by GiST indexes, but not by GIN indexes. は、GINインデックスではなくGiSTインデックスによって非常に効率的に実装できます。

Beginning in <productname>PostgreSQL</productname> 9.1, these index types also support index searches for <literal>LIKE</literal> and <literal>ILIKE</literal>, for example PostgreSQL 9.1から、これらのインデックス種類はLIKEおよびILIKEにおけるインデックス検索をサポートします。 以下に例を示します。

SELECT * FROM test_trgm WHERE t LIKE '%foo%bar';

The index search works by extracting trigrams from the search string and then looking these up in the index. The more trigrams in the search string, the more effective the index search is. Unlike B-tree based searches, the search string need not be left-anchored. インデックス検索は、検索文字列からトライグラムを抽出し、それらをインデックスから検索することによって動作します。 検索文字列内のトライグラムが多ければ、よりインデックス検索が効率的になります。 B-treeを基にした検索とは異なり、検索文字列の左側が固定されている必要はありません。

Beginning in <productname>PostgreSQL</productname> 9.3, these index types also support index searches for regular-expression matches (<literal>~</literal> and <literal>~*</literal> operators), for example PostgreSQL 9.3から、これらの種類のインデックスは正規表現一致(~および~*演算子)に対するインデックス検索もサポートします。 以下に例を示します。

SELECT * FROM test_trgm WHERE t ~ '(foo|bar)';

The index search works by extracting trigrams from the regular expression and then looking these up in the index. The more trigrams that can be extracted from the regular expression, the more effective the index search is. Unlike B-tree based searches, the search string need not be left-anchored. インデックス検索は、正規表現からトライグラムを抽出し、それらをインデックスから検索することで動作します。 より多くのトライグラムが正規表現から抽出される場合、インデックス検索はより効率的になります。 B-treeを基にした検索と異なり、検索文字列は先頭一致である必要はありません。

For both <literal>LIKE</literal> and regular-expression searches, keep in mind that a pattern with no extractable trigrams will degenerate to a full-index scan. LIKEおよび正規表現検索の両方で、トライグラムが抽出されないパターンでは完全インデックススキャンより性能が落ちることに注意してください。

The choice between GiST and GIN indexing depends on the relative performance characteristics of GiST and GIN, which are discussed elsewhere. GiSTまたはGINインデックスの選択は、他で説明されるGiSTとGINの相対的な性能特性に依存します。 これについては、別途議論されています。

F.35.6. 参考 #

<title>References</title>

GiST Development Site GiST開発サイト http://www.sai.msu.su/~megera/postgres/gist/

Tsearch2 Development Site Tsearch2開発サイト http://www.sai.msu.su/~megera/postgres/gist/tsearch/V2/

F.35.7. 作者 #

<title>Authors</title>

Oleg Bartunov , Moscow, Moscow University, Russia

Teodor Sigaev , Moscow, Delta-Soft Ltd.,Russia

Alexander Korotkov , Moscow, Postgres Professional, Russia

Documentation: Christopher Kings-Lynne 文書作成: Christopher Kings-Lynne

This module is sponsored by Delta-Soft Ltd., Moscow, Russia. 本モジュールはロシアモスクワのDelta-Soft Ltd.による後援です。