How to use uuid with postgresql gist index type?

与世无争的帅哥 提交于 2019-12-05 03:29:42

Postgres 10 or newer

btree_gist now also covers the data type uuid, like Paul commented. (And some other data types, remarkably all enum types.)

Now all you need to do: install the extension once per database:

CREATE EXTENSION btree_gist;

Then your index should just work.

Related:


Postgres 9.6 or older

(Original answer.)
Normally I would suggest the additional module btree_gist, but the type uuid is not covered by it.

In theory, since a UUID is a 128-bit quantity (per documentation), the most efficient way would be to convert it to two bigint or float8 for the purpose of the index. But none of these casts are defined in standard Postgres.

I found a stab in that direction in the pqsql-hackers list, but it seems unsuccessful.

The remaining option is a functional GiST index on the text representation:

CREATE INDEX idx_leaderboads_values_gist
ON leaderboard_entry USING gist (id_leaderboard, cast("value" AS text));

To make use of this functional index, queries must match that expression. You can use the shorthand "value"::text in queries (but not in the index definition without adding more parentheses).

Aside: do not use value as column name it's a reserved word in standard SQL.

The question is: why do you need the GiST index. The best solution depends on the objective.

If you're using Postgres 10, and you migrated your database from a previous version using dump/restore, you may need to run:

ALTER EXTENSION btree_gist UPDATE;

in order to get gist indexes to work with UUID's.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!