- Mastering PostgreSQL 10
- Hans Jürgen Sch?nig
- 263字
- 2021-06-30 19:03:55
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 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:
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 in 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.
- 網(wǎng)頁編程技術(shù)
- Getting Started with MariaDB
- 腦動力:PHP函數(shù)速查效率手冊
- 大數(shù)據(jù)安全與隱私保護
- 大數(shù)據(jù)技術(shù)與應(yīng)用
- Machine Learning with Apache Spark Quick Start Guide
- 激光選區(qū)熔化3D打印技術(shù)
- 計算機組網(wǎng)技術(shù)
- Citrix? XenDesktop? 7 Cookbook
- HBase Essentials
- 西門子S7-1200/1500 PLC從入門到精通
- CPLD/FPGA技術(shù)應(yīng)用
- 人工智能:重塑個人、商業(yè)與社會
- 細節(jié)決定交互設(shè)計的成敗
- 機器學(xué)習(xí)公式詳解