Create timestamp index from JSON on PostgreSQL

前端 未结 1 750
我在风中等你
我在风中等你 2020-12-06 19:18

I have a table on PostgreSQL with a field named data that is jsonb with a lot of objects, I want to make an index to speed up the queries. I\'m usi

1条回答
  •  不思量自难忘°
    2020-12-06 19:44

    This expression won't be allowed in the index either:

    (CAST(data->>'created_at' AS timestamp) at time zone 'UTC')
    

    It's not immutable, because the first cast depends on your DateStyle setting (among other things). Doesn't help to translate the result to UTC after the function call, uncertainty has already crept in ...

    The solution is a function that makes the cast immutable by fixing the time zone (like @a_horse already hinted).

    I suggest to use to_timestamp() instead of the cast (which is also not IMMUTABLE) to rule out some source of trouble - DateStyle being one.

    CREATE OR REPLACE FUNCTION f_cast_isots(text)
      RETURNS timestamptz AS
    $$SELECT to_timestamp($1, 'YYYY-MM-DD HH24:MI')$$  -- adapt to your needs
      LANGUAGE sql IMMUTABLE;
    

    Note that this returns timestamptz. Then:

    CREATE INDEX foo ON t (f_cast_isots(data->>'created_at'));
    

    Detailed explanation for this technique in this related answer:

    • Does PostgreSQL support "accent insensitive" collations?

    Related:

    • Query on a time range ignoring the date of timestamps

    0 讨论(0)
提交回复
热议问题