I have a table with schema along the lines of:

  account VARCHAR(64) NOT NULL,
  json    JSONB       NOT NULL

And I'd like to create an index on it that will allow me to run queries such as:

FROM table1
WHERE account = :account
  AND json ... -- Some JSON search expression

So I tried adding an index on this table like this:

CREATE INDEX index1 ON table1 USING GIN (account, json);

And I'm getting:

ERROR: data type character varying has no default operator class for
       access method "gin"
Hint: You must specify an operator class for the index or define a default
      operator class for the data type.

I've tried adding _varchar_ops:

CREATE INDEX index1 ON table1 USING GIN (account _varchar_ops, json);

And then I got:

ERROR: operator class "_varchar_ops" does not accept data type character varying

I realize I can simply add the account as a field of every json document, but I'd like to avoid this duplicity and potential gotcha or room for discrepancy, and just have the account as a column.

How can I solve this and get a combined index on these two fields?


Two indexes

Simply create two separate indexes. PostgreSQL will use both where appropriate.

CREATE INDEX ON table1 (account);

Using an extension

Or you can use the btree_gin.

btree_gin provides sample GIN operator classes that implement B-tree equivalent behavior for the data types int2, int4, int8, float4, float8, timestamp with time zone, timestamp without time zone, time with time zone, time without time zone, date, interval, oid, money, "char", varchar, text, bytea, bit, varbit, macaddr, inet, and cidr.

It looks like this,

CREATE INDEX ON table1 USING gin (account,json);

Under normal circumstances, I'd likely use two indexes.

| improve this answer | |
  • So for my example query Postgres will take advantage of both indexes? – Amir Abiri Sep 23 '17 at 21:26
  • 1
    Depends on the planner estimates, but it could use two indexes – Evan Carroll Sep 23 '17 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.