官术网_书友最值得收藏!

  • Mastering PostgreSQL 12
  • Hans Jürgen Sch?nig
  • 271字
  • 2021-08-20 10:00:27

Adding functional indexes

So far, you have seen how to index the content of a column as it is. However, this might not always be what you really want. Therefore, PostgreSQL allows ./' as the creation of functional indexes. The basic idea is very simple: instead of indexing a value, the output of a function is stored in the index.

The following example shows how the cosine of the id column can be indexed:

test=# CREATE INDEX idx_cos ON t_random (cos(id));
CREATE INDEX
test=# ANALYZE; ANALYZE

All you have to do is put the function on the list of columns, and you are done. Of course, this won't work for all kinds of functions. Functions can only be used if their output is immutable, as shown in the following example:

test=# SELECT age('2010-01-01 10:00:00'::timestamptz); 
age
-------------------------
6 years 9 mons 14:00:00
(1 row)

Functions such as age are not really suitable for indexing because their output is not constant. Time goes on and, consequently, the output of age will change too. PostgreSQL will explicitly prohibit functions that have the potential to change their result given the same input. The cos function is fine in this respect because the cosine of a value will still be the same 1,000 years from now.

To test the index, I have written a simple query to show what will happen:

test=# EXPLAIN SELECT * FROM t_random WHERE cos(id) = 10;  
QUERY PLAN
----------------------------------------------------------------------
Index Scan using idx_cos on t_random (cost=0.43..8.45 rows=1 width=9)
Index Cond: (cos((id)::double precision) = '10'::double precision)
(2 rows)

As expected, the functional index will be used just like any other index.

主站蜘蛛池模板: 嘉荫县| 仪征市| 湘潭县| 曲麻莱县| 商洛市| 隆安县| 邢台县| 桂阳县| 奉贤区| 勐海县| 和林格尔县| 元氏县| 新昌县| 仁寿县| 邯郸市| 郎溪县| 清涧县| 吴江市| 古蔺县| 静海县| 农安县| 陈巴尔虎旗| 汶川县| 合肥市| 山西省| 鄂伦春自治旗| 宾阳县| 普宁市| 涪陵区| 麻城市| 周口市| 阜宁县| 北京市| 茂名市| 谷城县| 长丰县| 安溪县| 屏东县| 仁怀市| 湖口县| 南漳县|