Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create postgresql index on text column casted to array

I have a postgresql table that has a column with data type = 'text' in which I need to create an index which involves this column being type casted to integer[]. However, whenever I try to do so, I get the following error:

ERROR: functions in index expression must be marked IMMUTABLE

Here is the code:

create table test (a integer[], b text);

insert into test values ('{10,20,30}','{40,50,60}');

CREATE INDEX index_test on test USING GIN ((   b::integer[]      ));

Note that one potential workaround is to create a function that is marked as IMMUTABLE that takes in a column value and performs the type casting within the function, but the problem (aside from adding overhead) is that I have many different 'target' array data types (EG: text[], int2[], int4[], etc...), and it would not be possible to create a separate function for each potential target array data type.

like image 269
archmeta Avatar asked Aug 25 '11 03:08

archmeta


People also ask

What is text [] in PostgreSQL?

PostgreSQL supports a character data type called TEXT. This data type is used to store character of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same.

How do I index an array in PostgreSQL?

To index arrays in PostgreSQL, it's best to use a GIN or GiST index. Using either index has its benefits and drawbacks; however, GiST indexes were primarily developed for geometric datatypes, while GIN indexes were designed for arrays.

How do I create an array in PostgreSQL?

To create a column of an array type, the [] symbol is used. The following examples illustrate this: create table contacts ( first_name varchar, last_name varchar, phone_numbers varchar[] ); create table player_scores ( player_number integer, round_scores integer[] );


1 Answers

Answered in this thread on the PostgreSQL mailing lists. Click on "Follow-ups" or "next by thread" in the links after the post to follow the (short) thread on the topic.

There's no recipe given there, but Tom's just talking about defining an explicit cast from text[] to integer[]. If time permits I'll flesh this answer out with an example.

like image 81
Craig Ringer Avatar answered Oct 08 '22 10:10

Craig Ringer