【问题标题】:How to index a varchar array in Postgresql using array_to_string?如何使用 array_to_string 在 Postgresql 中索引 varchar 数组?
【发布时间】:2015-10-05 15:02:04
【问题描述】:

我希望在 postgresql 9.3 的 varchar 数组列中设置索引。有人告诉我使用array_to_string(col) 设置它,但我真的不明白它是如何工作的。我想出了以下声明:

CREATE INDEX CONCURRENTLY rtb_id_search ON sites USING GIN(array_to_string(rtb_id, ''));

但是,postgresql 抱怨:

 ERROR:  functions in index expression must be marked IMMUTABLE

【问题讨论】:

    标签: postgresql indexing


    【解决方案1】:

    您希望加速哪些操作? GIN indes 直接支持数组:

    create table foo(a text[]);
    create index on foo using gin (a);
    set enable_seqscan to off;
    

    可能存在一些问题,因为并非所有数组运算符都受索引支持。但几乎是这样。

    postgres=#解释 select * from foo where a @> ARRAY['a']; ┌────────────────────────────────────────────────── ────────────────────────┐ │ 查询计划 │ ╞═════════════════════════════════════════════════ ═══════════════════════╡ │ foo 上的 Bitmap Heap Scan (cost=8.05..18.20 rows=7 width=32) │ │ 复查条件:(a @> '{a}'::text[]) │ │ -> foo_a_idx 上的位图索引扫描 (cost=0.00..8.05 rows=7 width=0) │ │ 索引条件:(a @> '{a}'::text[]) │ └────────────────────────────────────────────────── ────────────────────────┘ (4 行)

    【讨论】:

      【解决方案2】:
      create function string_array_to_string(text[], text, text) returns text as $$
         select array_to_string($1, $2, $3)
      $$ language sql cost 1 immutable;
      
      create index concurrently sites_rtb_ids on sites using gin (string_array_to_string(rtb_ids, ' ', ' ') gin_trgm_ops);
      

      这是创建索引的方法。使用的函数需要标记为不可变。

      【讨论】:

      • 这适用于在数组列上创建gin_trgm_ops 索引。但是我无法让 Postgres 使用这个索引来处理我尝试的任何查询:(
      • 我也一直无法让 postgres 使用索引。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多