Compare commits

...

338 Commits
v0.1.7 ... bas

Author SHA1 Message Date
Andrew Kane
bb72a6c063 Test BufferAccessStrategy [skip ci] 2023-04-10 22:07:58 -07:00
Andrew Kane
f32f695844 Improved notice [skip ci] 2023-04-10 21:31:33 -07:00
Andrew Kane
1b013a94f7 Added notice when index created with little data [skip ci] 2023-04-10 21:28:24 -07:00
Andrew Kane
00148dfa1f Improved indexing docs [skip ci] 2023-04-10 21:12:25 -07:00
Andrew Kane
67fc791d95 Improved indexing docs [skip ci] 2023-04-10 21:04:46 -07:00
Andrew Kane
8bf360ed84 Updated header [skip ci] 2023-04-02 11:24:46 -07:00
Andrew Kane
f79d28347b Updated installation notes [skip ci] 2023-04-02 11:21:57 -07:00
Andrew Kane
20cf63de0a Updated readme [skip ci] 2023-04-02 10:56:37 -07:00
Andrew Kane
587cbcf15b Updated readme [skip ci] 2023-04-02 10:46:44 -07:00
Andrew Kane
c09edb5b8f Moved instructions [skip ci] 2023-04-02 10:39:41 -07:00
Will Laurance
c63501cca4 Update readme to show example usage of PG_CONFIG (#79) 2023-04-02 10:34:02 -07:00
Andrew Kane
58f0c922d2 Updated readme [skip ci] 2023-04-02 10:24:21 -07:00
Andrew Kane
36e73d2818 Updated readme [skip ci] 2023-04-01 20:06:18 -07:00
Andrew Kane
dd92d0ece3 Updated readme [skip ci] 2023-04-01 20:04:47 -07:00
Andrew Kane
6ede7681a5 Updated readme [skip ci] 2023-04-01 19:47:13 -07:00
Andrew Kane
8733729149 Updated readme [skip ci] 2023-04-01 19:45:13 -07:00
Andrew Kane
03a5789132 Updated readme [skip ci] 2023-04-01 19:44:23 -07:00
Andrew Kane
e5b612a856 Updated readme [skip ci] 2023-04-01 19:34:21 -07:00
Andrew Kane
9a7d3532f5 Updated readme [skip ci] 2023-04-01 19:32:26 -07:00
Andrew Kane
91315dfeff Added additional instructions for Ubuntu, Debian, and Windows [skip ci] 2023-04-01 17:42:44 -07:00
Andrew Kane
6e3101d527 Updated Dockerfile [skip ci] 2023-04-01 13:31:52 -07:00
Andrew Kane
96ae1a6a72 Added PG_MAJOR arg to Dockerfile [skip ci] 2023-04-01 13:15:00 -07:00
Andrew Kane
55aeba8bd6 Added lists to example [skip ci] 2023-03-31 22:12:35 -07:00
Andrew Kane
aebe1bae02 Updated readme [skip ci] 2023-03-31 21:55:24 -07:00
Andrew Kane
14355b9312 Updated readme [skip ci] 2023-03-31 21:46:38 -07:00
Andrew Kane
b5c66d0416 Updated readme [skip ci] 2023-03-31 21:36:25 -07:00
Andrew Kane
f534d9878a Updated readme [skip ci] 2023-03-31 21:31:38 -07:00
Andrew Kane
f3df137db6 Improved indexing instructions [skip ci] 2023-03-31 21:28:45 -07:00
Andrew Kane
489cdb5068 Added delete example [skip ci] 2023-03-31 20:02:22 -07:00
Andrew Kane
161f48793e Updated readme [skip ci] 2023-03-31 19:59:53 -07:00
Andrew Kane
f0f7ffca41 Updated readme [skip ci] 2023-03-31 19:34:39 -07:00
Andrew Kane
138d9be616 Added storage examples [skip ci] 2023-03-31 19:17:26 -07:00
Andrew Kane
fb98e73255 Updated readme [skip ci] 2023-03-31 18:55:51 -07:00
Andrew Kane
4754cac40c Updated readme [skip ci] 2023-03-31 18:47:15 -07:00
Andrew Kane
8432efb7d8 Added cosine similarity example [skip ci] 2023-03-31 18:34:36 -07:00
Andrew Kane
c38410259c Updated header [skip ci] 2023-03-31 16:59:21 -07:00
Andrew Kane
609d9fbf0a Updated header [skip ci] 2023-03-31 16:54:14 -07:00
Andrew Kane
7946424639 Updated header [skip ci] 2023-03-31 16:49:40 -07:00
Andrew Kane
d51310dfa0 Updated readme [skip ci] 2023-03-31 16:38:09 -07:00
Andrew Kane
30f2893aeb Updated readme [skip ci] 2023-03-31 16:30:42 -07:00
Andrew Kane
5d0f88529e Updated readme [skip ci] 2023-03-31 16:28:27 -07:00
Andrew Kane
1d020abdd1 Added auto-vectorized comments [skip ci] 2023-03-31 16:20:10 -07:00
Andrew Kane
d0fdd42652 Added comment [skip ci] 2023-03-31 13:37:33 -07:00
Andrew Kane
8473468925 Added instructions for Yum - #76 2023-03-30 15:39:27 -07:00
Andrew Kane
9c01524466 Updated readme [skip ci] 2023-03-26 23:39:09 -07:00
Andrew Kane
121baa411e Added debug message for index scan 2023-03-26 12:45:44 -07:00
Andrew Kane
50005d7326 Updated CI [skip ci] 2023-03-26 09:46:21 -07:00
Andrew Kane
ec12d79cbc Added link to pgvector-perl [skip ci] 2023-03-23 21:42:43 -07:00
Andrew Kane
d3eb56df07 Improved tests 2023-03-22 16:35:56 -07:00
Andrew Kane
13f7aa50c3 Added Render link [skip ci] 2023-03-22 16:29:06 -07:00
Andrew Kane
81e9e72fbc Updated guidance on lists [skip ci] 2023-03-22 14:00:47 -07:00
Andrew Kane
8d95510302 Updated readme [skip ci] 2023-03-22 13:32:25 -07:00
Andrew Kane
53bb2ed0cd Updated Homebrew instructions [skip ci] 2023-03-21 13:20:57 -07:00
Andrew Kane
fac8b9c8d9 Version bump to 0.4.1 [skip ci] 2023-03-21 12:39:59 -07:00
Andrew Kane
4e68f4f800 Updated comment [skip ci] 2023-03-21 11:55:26 -07:00
Andrew Kane
b69ac51ad7 Added comment [skip ci] 2023-03-21 11:43:30 -07:00
Andrew Kane
29c7af5d18 Improved test 2023-03-21 11:32:16 -07:00
Andrew Kane
bc9e2a37ec Improved performance of cosine distance 2023-03-21 11:25:25 -07:00
Andrew Kane
18eb04e278 Updated readme [skip ci] 2023-03-12 14:09:36 -07:00
Andrew Kane
42da2b334b Restored previous behavior and added comment 2023-03-12 13:57:40 -07:00
Andrew Kane
dbfc6a35d9 Improved vacuumcleanup stats 2023-03-12 13:34:26 -07:00
Andrew Kane
bbae64b784 Removed unneeded query from test 2023-03-12 13:26:23 -07:00
Andrew Kane
a6e8f36415 Updated readme [skip ci] 2023-03-12 13:15:47 -07:00
Andrew Kane
44985abbc6 Updated comment [skip ci] 2023-03-12 13:15:31 -07:00
Andrew Kane
9897ba7f64 Fixed CI 2023-03-12 13:13:04 -07:00
Andrew Kane
bb75ce2cf2 Fixed index scan count 2023-03-12 12:24:20 -07:00
Andrew Kane
385b2437a9 Updated readme [skip ci] 2023-03-05 18:18:03 -08:00
Andrew Kane
6c1536ee78 Moved section [skip ci] 2023-03-05 18:16:43 -08:00
Andrew Kane
4d8eae1c3e Updated readme [skip ci] 2023-03-05 18:13:32 -08:00
Andrew Kane
68378066a8 Added example of AVG [skip ci] 2023-03-05 17:54:02 -08:00
Andrew Kane
4f8620fe9e Added EXPLAIN ANALYZE to readme [skip ci] 2023-03-05 17:48:01 -08:00
Andrew Kane
a1ab0a453c Moved section [skip ci] 2023-03-05 17:44:53 -08:00
Andrew Kane
f1983ce672 Added section on querying - #64 [skip ci] 2023-03-05 17:34:49 -08:00
Andrew Kane
0a3615b82f Updated readme [skip ci] 2023-03-05 14:17:39 -08:00
Andrew Kane
e8a67dcf1c Added link to pgvector-lua [skip ci] 2023-03-05 13:44:52 -08:00
Andrew Kane
e83121eee4 Added link to pgvector-dotnet [skip ci] 2023-03-05 11:45:40 -08:00
Andrew Kane
77154f8cbb Updated readme [skip ci] 2023-03-03 16:33:44 -08:00
Andrew Kane
051c42a05a Updated readme [skip ci] 2023-03-03 16:28:23 -08:00
Andrew Kane
9077d85407 Reordered libraries [skip ci] 2023-03-03 16:18:55 -08:00
Andrew Kane
d74c82ff97 Updated pgvector-java link [skip ci] 2023-03-03 16:08:01 -08:00
Andrew Kane
cb6b7a3893 Added link to pgvector-scala [skip ci] 2023-03-03 11:50:03 -08:00
Andrew Kane
cb7d787d7c Added link to pgvector-julia [skip ci] 2023-03-02 22:16:23 -08:00
Andrew Kane
fc09ee200d Updated readme [skip ci] 2023-03-02 19:33:21 -08:00
Andrew Kane
eedcd64e08 Updated readme [skip ci] 2023-03-02 19:27:09 -08:00
Andrew Kane
c1671a4982 Updated readme [skip ci] 2023-03-02 19:22:00 -08:00
Andrew Kane
010055b288 Updated readme [skip ci] 2023-03-02 16:57:01 -08:00
Andrew Kane
8b759b695b Added link to pgvector-r [skip ci] 2023-03-02 16:48:14 -08:00
Andrew Kane
e1e53860d4 Added log to .gitignore [skip ci] 2023-02-26 09:57:31 -08:00
Andrew Kane
a85250c7bc Added platform to Docker task [skip ci] 2023-02-25 16:11:28 -08:00
Andrew Kane
4984411906 Added dylib to .gitignore [skip ci] 2023-02-25 15:28:00 -08:00
Andrew Kane
e4b0d41d30 Fixed warning 2023-02-23 14:17:31 -08:00
Andrew Kane
1b16a28906 Added test for casting from numeric[] 2023-02-23 14:15:50 -08:00
Andrew Kane
0b3dc0887f Fixed compilation with Postgres 16 - fixes #61 2023-02-23 14:08:27 -08:00
Andrew Kane
bb71b22e2e Updated readme [skip ci] 2023-02-22 19:42:40 -08:00
Andrew Kane
3b9df1c145 Moved to thread [skip ci] 2023-01-28 13:56:44 -08:00
Andrew Kane
11f66e6010 Added Supabase to readme [skip ci] 2023-01-28 11:13:47 -08:00
Andrew Kane
9b13db5c5c Updated link [skip ci] 2023-01-18 04:31:42 -08:00
Andrew Kane
ca9d4ed82a Updated readme [skip ci] 2023-01-13 10:30:34 -08:00
Andrew Kane
b1ffe2d4d3 Updated readme [skip ci] 2023-01-13 00:41:13 -08:00
Andrew Kane
246f8814bc Updated readme [skip ci] 2023-01-13 00:40:37 -08:00
Andrew Kane
a5d8bb2688 Added link to feedstock [skip ci] 2023-01-12 02:15:18 -08:00
Andrew Kane
95e496ba00 Added conda-forge to readme - closes #47 [skip ci] 2023-01-12 02:02:18 -08:00
Andrew Kane
6bfc2cb9a1 Use table for libraries [skip ci] 2023-01-11 14:34:33 -08:00
Andrew Kane
25d6747721 Version bump to 0.4.0 [skip ci] 2023-01-11 11:36:25 -08:00
Andrew Kane
fce99e0472 Updated readme and changelog for 0.4.0 [skip ci] 2023-01-11 11:34:28 -08:00
Andrew Kane
ec415bf5c4 Added upgrade instructions for 0.4.0 [skip ci] 2023-01-11 11:32:47 -08:00
Andrew Kane
0111ffffbd Updated readme for 0.4.0 [skip ci] 2023-01-11 11:32:21 -08:00
Andrew Kane
7d1398d1a7 Updated Azure link [skip ci] 2023-01-10 23:13:27 -08:00
Andrew Kane
b6f1a82774 Added assertions to scan [skip ci] 2023-01-10 21:07:19 -08:00
Andrew Kane
7b0b6a7875 Increased max dimensions for vector from 1024 to 16000 and increased max dimensions for index from 1024 to 2000 2023-01-10 14:49:50 -08:00
Andrew Kane
42d0cf1a25 Changed storage for existing installations [skip ci] 2023-01-10 11:34:43 -08:00
Andrew Kane
d164fd35a8 Made dimensions configurable for vacuum test 2023-01-10 03:14:49 -08:00
Andrew Kane
13e0fa24fe Use memory context for inserts 2023-01-10 02:53:58 -08:00
Andrew Kane
7c65fd13c1 Detoast once for all calls 2023-01-10 02:35:08 -08:00
Andrew Kane
9616a611c3 Added test for storage 2023-01-10 02:08:09 -08:00
Andrew Kane
474933ae39 Improved error message [skip ci] 2023-01-10 01:22:34 -08:00
Andrew Kane
b1237c7c4e Added separate dimensions limit for ivfflat indexes 2023-01-10 01:20:25 -08:00
Andrew Kane
66108cb406 Restored change to extended storage 2023-01-10 01:13:19 -08:00
Andrew Kane
8c3eb51ddc Added comment [skip ci] 2023-01-10 01:03:27 -08:00
Andrew Kane
915cf35e27 Use memory context for adding samples 2023-01-10 01:03:16 -08:00
Andrew Kane
ec800ef903 Use memory context for building index 2023-01-10 00:53:33 -08:00
Andrew Kane
4a2f20f5fc Reverted change to extended storage for now (causes high memory during distance calculation in BuildCallback) 2023-01-09 17:23:45 -08:00
Andrew Kane
e2b103a343 Updated version check [skip ci] 2023-01-09 15:54:44 -08:00
Andrew Kane
5d82d7bf99 Improved test [skip ci] 2022-12-30 19:30:17 -08:00
Andrew Kane
7c74d8ab75 Improved test [skip ci] 2022-12-30 19:29:19 -08:00
Andrew Kane
8dbd39f641 Improved test [skip ci] 2022-12-30 19:28:12 -08:00
Andrew Kane
d4681dd898 Simplified test 2022-12-30 19:25:40 -08:00
Andrew Kane
14984a08ea Improved avg test 2022-12-30 18:54:53 -08:00
Andrew Kane
30e07a6943 Updated readme [skip ci] 2022-12-30 18:34:51 -08:00
Andrew Kane
be26cf2f82 Updated readme [skip ci] 2022-12-30 18:29:22 -08:00
Andrew Kane
f205312430 Added float_overflow_error function for Postgres 11 2022-12-30 17:55:02 -08:00
Andrew Kane
085b75b727 Updated readme [skip ci] 2022-12-30 17:39:03 -08:00
Andrew Kane
3d8543f9ff Fixed include 2022-12-30 17:33:00 -08:00
Andrew Kane
8cbf0254bb Fixed TYPALIGN_DOUBLE error 2022-12-30 17:26:41 -08:00
Andrew Kane
e09f93cba7 Added avg aggregate for vector - closes #51 2022-12-30 17:22:25 -08:00
Andrew Kane
b400ac0f36 Insert before unlocking new buffer 2022-12-23 20:08:32 -08:00
Andrew Kane
aa62b42a9a Updated changelog [skip ci] 2022-12-23 19:19:15 -08:00
Andrew Kane
46b8294d5f Fixed script for Postgres < 13 [skip ci] 2022-12-23 19:16:44 -08:00
Andrew Kane
989b4c4208 Updated license year [skip ci] 2022-12-23 19:00:52 -08:00
Andrew Kane
fa491cd906 Changed storage for vector from plain to extended 2022-12-23 18:59:18 -08:00
Andrew Kane
00b767b107 Use DatumGetVector 2022-12-23 12:33:55 -08:00
Andrew Kane
1823024d9c Use consistent indentation [skip ci] 2022-12-23 12:04:52 -08:00
Andrew Kane
563f888ef1 Test with multiple versions of Ubuntu 2022-12-23 10:58:24 -08:00
Andrew Kane
141fea8d08 Use del on Windows 2022-12-23 10:54:34 -08:00
Andrew Kane
83407a9e23 Improved error handling on CI 2022-12-23 10:10:46 -08:00
Andrew Kane
0b1d36bb33 Added check for PGROOT 2022-12-23 09:46:07 -08:00
Andrew Kane
6d4ac36d50 Added uninstall task for Windows [skip ci] 2022-12-23 09:18:25 -08:00
Andrew Kane
e2f33dfdba Added clean task for Windows 2022-12-23 09:02:15 -08:00
Andrew Kane
3f3ba5b8e7 Set PROVE in Makefile if needed 2022-12-23 08:22:38 -08:00
Andrew Kane
0f69cc789a Combined sampling table and performing k-means phases 2022-12-23 08:07:09 -08:00
Andrew Kane
b09e14ce14 Dropped support for Postgres 10 2022-12-23 08:03:03 -08:00
Andrew Kane
1b5cb17f22 Removed code for Postgres < 10 2022-12-22 21:21:29 -08:00
Andrew Kane
7314d8b05a Improved CI [skip ci] 2022-12-09 01:56:00 -08:00
Andrew Kane
0a46adb112 Skip tests for certain branches [skip ci] 2022-12-09 01:48:38 -08:00
Andrew Kane
8c81213592 Improved installcheck on Windows 2022-12-08 22:33:19 -08:00
Andrew Kane
f77b044303 Simplified tests 2022-12-08 22:11:49 -08:00
Andrew Kane
fab7b50c3a Updated readme [skip ci] 2022-12-08 16:03:22 -08:00
Andrew Kane
9e2e726010 Improved macros [skip ci] 2022-12-08 15:42:22 -08:00
Andrew Kane
2621f9f947 Added experimental support for Windows (including auto-vectorization) - closes #49 2022-12-08 13:27:26 -08:00
Andrew Kane
4fbe55f97e Split CI into separate groups of steps 2022-12-08 00:26:48 -08:00
Andrew Kane
9c9489e888 Removed nested FLEXIBLE_ARRAY_MEMBER for Windows 2022-12-07 19:53:48 -08:00
Andrew Kane
d376011087 Added VectorArrayFree 2022-12-07 19:45:44 -08:00
Andrew Kane
5107e057ad Improved CI [skip ci] 2022-12-07 16:35:03 -08:00
Andrew Kane
1c1812aeac Updated indentation [skip ci] 2022-12-07 16:34:01 -08:00
Andrew Kane
da12d9d8b0 Fixed copy test on Windows [skip ci] 2022-12-07 16:10:35 -08:00
Andrew Kane
de26e1e78a Perform version check earlier [skip ci] 2022-12-07 15:52:35 -08:00
Andrew Kane
8691d2ad53 Include port.h to fix buggy strtof on some platforms 2022-12-07 15:47:39 -08:00
Andrew Kane
573200c188 Use pg_prng_uint32 for Postgres 15 2022-12-07 15:28:11 -08:00
Andrew Kane
cd7cab804f Added port.h for random() function on Windows 2022-12-07 15:17:32 -08:00
Andrew Kane
84a8bdd661 Fixed FLOAT_SHORTEST_DECIMAL_LEN for Postgres < 12 [skip ci] 2022-12-02 10:54:14 -08:00
Andrew Kane
7a13a6cd3c Updated changelog [skip ci] 2022-12-01 21:23:22 -08:00
Andrew Kane
35d5cb9f06 Fixed CI (behavior of extra_float_digits changed between Postgres 11 and 12) 2022-12-01 21:07:57 -08:00
Andrew Kane
bc6b9e4bba Added more tests for text output 2022-12-01 20:45:27 -08:00
Andrew Kane
d605948be4 Updated changelog [skip ci] 2022-12-01 20:28:17 -08:00
Andrew Kane
37a784d3f6 Fixed improved vector text representation for Postgres < 12 2022-12-01 15:41:12 -08:00
Andrew Kane
c74bb5495b Improved vector text representation - fixes #46 2022-12-01 14:57:47 -08:00
Andrew Kane
cc35af160e Use strtof like float4in to avoid a double-rounding problem 2022-12-01 14:41:09 -08:00
Andrew Kane
a7f712b5a4 Version bump to 0.3.2 [skip ci] 2022-11-22 13:46:33 -08:00
Andrew Kane
a532d82bda Use palloc_extended for halfcdist 2022-11-17 19:52:46 -08:00
Andrew Kane
ccec96ba54 Fixed invalid memory alloc request size error - fixes #43 2022-11-17 14:12:49 -08:00
Andrew Kane
b7c5849ba7 Switched to dev-files option on CI 2022-11-03 15:24:12 -07:00
Andrew Kane
135147893a Updated comment [skip ci] 2022-11-02 16:55:20 -07:00
Andrew Kane
00391953dd Updated comment [skip ci] 2022-11-02 16:54:27 -07:00
Andrew Kane
81bba1f37e Improved order of insert operations 2022-11-02 16:41:56 -07:00
Andrew Kane
2d8b7e5f81 Version bump to 0.3.1 [skip ci] 2022-11-02 15:24:29 -07:00
Andrew Kane
cebae5e5ff Fixed link [skip ci] 2022-11-02 15:21:44 -07:00
Andrew Kane
4c3332fc4d Added upgrade notes [skip ci] 2022-11-02 15:20:53 -07:00
Andrew Kane
386a3b5dd5 Improved test for inserts 2022-11-02 14:29:41 -07:00
Andrew Kane
fb819eb8b2 Added comment [skip ci] 2022-11-02 12:56:32 -07:00
Andrew Kane
3f8407460e Improved test 2022-11-02 12:50:50 -07:00
Andrew Kane
059e88dda5 Fixed randomness in WAL test 2022-11-02 12:41:54 -07:00
Andrew Kane
12f158d4bb Fixed warning 2022-11-02 12:27:09 -07:00
Andrew Kane
2a3c0a769a Ensure only one backend tries to extend relation at the same time - fixes #41 2022-11-02 12:23:49 -07:00
Andrew Kane
349d844fa1 Fixed issue with uninitialized pages - fixes #41 2022-11-02 11:01:47 -07:00
Andrew Kane
a57ca81d8f Switched to runtime check 2022-10-30 12:07:03 -07:00
Andrew Kane
dc4a79a7e7 Added check for indexing overflow 2022-10-30 12:01:24 -07:00
Andrew Kane
1652a130c5 Removed unused assignments 2022-10-30 11:55:17 -07:00
Andrew Kane
a6743bd206 Added .bc to .gitignore 2022-10-30 11:54:58 -07:00
Andrew Kane
e25627074f Removed unused code [skip ci] 2022-10-30 11:49:06 -07:00
Andrew Kane
b3cad93f3a Fixed segmentation fault with index creation when lists > 6500 - fixes #42 2022-10-30 11:14:58 -07:00
Andrew Kane
379a76098e Fixed version in META.json [skip ci] 2022-10-15 14:44:44 -07:00
Andrew Kane
5af768752f Version bump to 0.3.0 [skip ci] 2022-10-15 14:38:43 -07:00
Andrew Kane
f03bcc4fd8 Updated Dockerfile to Postgres 15 [skip ci] 2022-10-14 16:01:25 -07:00
Andrew Kane
74fc4b9aaa Added .pm to .editorconfig [skip ci] 2022-10-14 14:05:20 -07:00
Andrew Kane
6870ba96ba Removed Postgres 9.6 from CI 2022-10-14 13:47:07 -07:00
Andrew Kane
2575cfdaa8 Fixed CI 2022-10-14 13:45:16 -07:00
Andrew Kane
9ff5ceacca Dropped support for Postgres 9.6 [skip ci] 2022-10-14 13:44:13 -07:00
Andrew Kane
9a58ee609a Added Postgres 15 to CI 2022-10-14 13:42:04 -07:00
Andrew Kane
66a31bef36 Simplified define [skip ci] 2022-10-10 15:01:16 -07:00
Andrew Kane
163ecdf063 Use define for RandomDouble 2022-10-10 14:59:10 -07:00
Andrew Kane
c9c6b96eed Added support for Postgres 15 [skip ci] 2022-10-05 16:11:37 -07:00
Andrew Kane
48e9a6830b Added link to pgvector-elixir [skip ci] 2022-08-03 23:12:25 -07:00
Andrew Kane
f22b47ca46 Added link to pgvector-php - #30 [skip ci] 2022-08-03 13:50:34 -07:00
Andrew Kane
2a057c055c Updated example [skip ci] 2022-08-01 00:06:45 -07:00
Andrew Kane
b89b58b893 Updated examples to be runnable - fixes #24 [skip ci] 2022-07-31 22:36:46 -07:00
Andrew Kane
2e77650e1d Updated example [skip ci] 2022-07-31 22:34:03 -07:00
Andrew Kane
0a68b040fb DRY code 2022-07-31 21:56:44 -07:00
Andrew Kane
434dc904c1 Version bump to 0.2.7 [skip ci] 2022-07-31 21:42:15 -07:00
Andrew Kane
92a671eeb1 Revert "Commit pages with tuple"
This reverts commit 94eeb83abe.
2022-07-31 21:36:46 -07:00
Andrew Kane
94eeb83abe Commit pages with tuple 2022-07-31 21:29:29 -07:00
Andrew Kane
6866939090 Fixed indentation [skip ci] 2022-07-31 21:21:06 -07:00
Andrew Kane
ba2fb6ad8c Fixed order in IvfflatAppendPage 2022-07-31 21:03:57 -07:00
Andrew Kane
51fe8aff02 Fixed unexpected data beyond EOF error - fixes #29 2022-07-31 20:48:15 -07:00
Andrew Kane
df3dc151d5 Updated readme [skip ci] 2022-07-27 17:38:13 -07:00
Andrew Kane
6687430589 Fixed CI 2022-07-10 16:30:45 -04:00
Andrew Kane
f128a455d1 Made dimensions configurable for WAL test - #29 2022-07-10 16:01:05 -04:00
Andrew Kane
56cb5f3503 Version bump to 0.2.6 [skip ci] 2022-05-22 18:21:15 -07:00
Andrew Kane
ecbf46938f Moved metrics to separate function [skip ci] 2022-02-15 19:13:23 -08:00
Andrew Kane
4ca264ba02 Added Davies-Bouldin index [skip ci] 2022-02-15 19:08:47 -08:00
Andrew Kane
f5458414b8 Made recall test less flaky 2022-02-15 18:17:05 -08:00
Andrew Kane
e64ed39acb Disabled scan progress for sampling 2022-02-15 18:14:59 -08:00
Andrew Kane
0d025be9d3 Improved performance of index creation for Postgres < 12 2022-02-15 18:05:33 -08:00
Andrew Kane
fed60dce78 Added tests for lists 2022-02-15 17:04:20 -08:00
Andrew Kane
a37f5eea4a Improved compare method [skip ci] 2022-02-15 11:50:35 -08:00
Andrew Kane
4bdb27e85a Fixed style [skip ci] 2022-02-14 23:15:27 -08:00
Andrew Kane
38f869e0bd Added test for 100% recall 2022-02-14 23:13:36 -08:00
Andrew Kane
ad8acc00d4 Fixed spacing [skip ci] 2022-02-14 21:58:20 -08:00
Andrew Kane
01926a418e Print operator name for failed recall test [skip ci] 2022-02-14 21:52:31 -08:00
Andrew Kane
9658d3c1ad Made recall test less flaky 2022-02-14 21:49:08 -08:00
Andrew Kane
6b9c6516f4 Improved code 2022-02-14 21:41:27 -08:00
Andrew Kane
88be03a3fa Removed unused code 2022-02-14 21:37:53 -08:00
Andrew Kane
bf5b2c8d7e Use tuple id directly 2022-02-14 21:31:08 -08:00
Andrew Kane
ac65ec2856 Improved code [skip ci] 2022-02-14 19:38:59 -08:00
Andrew Kane
7bba0e2a01 Test recall for all operators 2022-02-14 15:22:53 -08:00
Andrew Kane
c35e9f3b84 Removed comment [skip ci] 2022-02-13 03:53:30 -08:00
Andrew Kane
9549d93260 Improved recall test 2022-02-13 03:08:39 -08:00
Andrew Kane
310809d0e5 Fixed warnings 2022-02-13 03:03:17 -08:00
Andrew Kane
ce72ca8620 Switched to heap for nearest lists for performance 2022-02-13 02:59:27 -08:00
Andrew Kane
4f2c937a1f Improved recall test 2022-02-13 02:35:28 -08:00
Andrew Kane
ff400ce5f1 Use macro for UpdateProgress 2022-02-12 23:56:28 -08:00
Andrew Kane
41d11c62d6 Fixed style [skip ci] 2022-02-12 22:14:57 -08:00
Andrew Kane
fa5e90585d Added inertia 2022-02-12 21:23:53 -08:00
Andrew Kane
71d2908be1 Fixed style [skip ci] 2022-02-12 20:47:25 -08:00
Andrew Kane
d0a1c1d0ed Added test for centers 2022-02-12 20:44:05 -08:00
Andrew Kane
8063201cdf Fixed indentation [skip ci] 2022-02-12 20:43:48 -08:00
Andrew Kane
2f52127bee Version bump to 0.2.5 [skip ci] 2022-02-11 18:50:04 -08:00
Andrew Kane
4778039ffa Added benchmarking to readme [skip ci] 2022-02-11 16:09:45 -08:00
Andrew Kane
e3c9d70acc Added to existing PG_CFLAGS 2022-02-11 16:06:25 -08:00
Andrew Kane
5971e28f8c Added more benchmarking [skip ci] 2022-02-11 16:05:45 -08:00
Andrew Kane
2da27e2f01 Updated name [skip ci] 2022-02-11 15:52:59 -08:00
Andrew Kane
7dd934913d Improved output [skip ci] 2022-02-11 15:51:14 -08:00
Andrew Kane
9b46987e73 Added support for benchmarking 2022-02-11 15:48:13 -08:00
Andrew Kane
868e1f99a4 Added todo [skip ci] 2022-02-11 15:14:09 -08:00
Andrew Kane
354271178f Added todo [skip ci] 2022-02-11 14:31:42 -08:00
Andrew Kane
fe9b218903 Reduced memory for unlogged tables [skip ci] 2022-02-11 13:57:53 -08:00
Andrew Kane
3cdd1c16fb Improved code [skip ci] 2022-02-11 13:55:39 -08:00
Andrew Kane
4f7a5c92da Use maxlen for check [skip ci] 2022-02-11 13:54:03 -08:00
Andrew Kane
9399575e02 Include samples size and centers size in check 2022-02-11 12:43:01 -08:00
Andrew Kane
e7539fe548 Added new centers size 2022-02-11 11:58:58 -08:00
Andrew Kane
61860ee6d9 Updated changelog [skip ci] 2022-02-11 11:49:25 -08:00
Andrew Kane
eb99730d87 Removed unnecessary cast [skip ci] 2022-02-11 03:43:31 -08:00
Andrew Kane
e5da5cc532 Add one to error message to ceil [skip ci] 2022-02-11 03:41:54 -08:00
Andrew Kane
f59b1184fc Calculate all allocation sizes 2022-02-11 03:33:43 -08:00
Andrew Kane
cab103a2e7 Fixed index creation exceeding maintenance_work_mem and fixed error when lists > 1600 2022-02-11 03:10:19 -08:00
Andrew Kane
0094b70a36 Updated changelog [skip ci] 2022-02-11 03:02:59 -08:00
Andrew Kane
46ed56d80f Use float instead of double for k-means to save memory 2022-02-11 01:56:28 -08:00
Andrew Kane
d390cc9fa6 Increased recall queries in test 2022-02-11 00:45:39 -08:00
Andrew Kane
02ae98791c Improved recall test 2022-02-11 00:43:01 -08:00
Andrew Kane
b64c7d6228 Improved test [skip ci] 2022-02-11 00:15:37 -08:00
Andrew Kane
76f117c81c Added test for array of vectors [skip ci] 2022-02-07 15:25:37 -08:00
Andrew Kane
5414b2bc9e Added link to pgvector-ruby [skip ci] 2022-02-07 00:52:46 -08:00
Andrew Kane
6ba583b587 Improved test style [skip ci] 2022-02-06 20:24:50 -08:00
Andrew Kane
da88217fd8 Fixed test style 2022-02-06 20:19:20 -08:00
Andrew Kane
d5da22f24b Fixed tests 2022-02-06 20:14:21 -08:00
Andrew Kane
062e220936 Test probes 2022-02-06 20:08:53 -08:00
Andrew Kane
3d2b867a58 Added recall test 2022-02-06 19:59:46 -08:00
Andrew Kane
5aeabc3648 Added comments on index handler [skip ci] 2022-02-06 15:26:18 -08:00
Andrew Kane
687ec6d8d7 Added amadjustmembers 2022-02-06 15:21:59 -08:00
Andrew Kane
51dc18d5b7 Added compiler error for unsupported versions of Postgres 2022-02-06 15:15:46 -08:00
Andrew Kane
cb108ebfd2 Removed reindexing section [skip ci] 2022-02-06 12:45:49 -08:00
Andrew Kane
12bc4eb036 Version bump to 0.2.4 [skip ci] 2022-02-06 12:14:43 -08:00
Andrew Kane
fd0e472316 Added test for vacuum 2022-02-06 12:06:27 -08:00
Andrew Kane
9b11b05cd7 Added comment for amcanreturn [skip ci] 2022-02-06 11:28:03 -08:00
Andrew Kane
ab079c1911 Added support for parallel vacuum 2022-02-06 11:25:38 -08:00
Andrew Kane
f4eaa3de1f Fixed issue with index not reusing space 2022-02-06 11:23:10 -08:00
Andrew Kane
e47675d6ae Updated changelog [skip ci] 2022-01-30 20:31:09 -08:00
Andrew Kane
20167ddc33 Updated readme [skip ci] 2022-01-30 20:06:59 -08:00
Andrew Kane
e14fa82626 Version bump to 0.2.3 [skip ci] 2022-01-30 19:59:47 -08:00
Andrew Kane
2ae4de83fe Improved error message for spherical k-means with one dimension 2022-01-30 11:57:52 -08:00
Andrew Kane
5d2c4883dc Fixed undeclared error 2022-01-29 23:28:23 -08:00
Andrew Kane
fc1de9806a Added tuples_done and tuples_total 2022-01-29 23:15:46 -08:00
Andrew Kane
e375dd33f3 Added FAQ to readme [skip ci] 2022-01-29 22:17:38 -08:00
Andrew Kane
b643ef637a Added indexing progress to readme [skip ci] 2022-01-29 20:25:06 -08:00
Andrew Kane
0ee5bfda65 Added comment [skip ci] 2022-01-29 20:12:00 -08:00
Andrew Kane
c5bec2a534 Improved interrupt handling during index creation 2022-01-29 19:50:03 -08:00
Andrew Kane
40f65dc8ba Updated changelog [skip ci] 2022-01-29 19:23:44 -08:00
Andrew Kane
9ec174137f Added build phase progress for Postgres 12+ 2022-01-29 19:19:16 -08:00
Andrew Kane
423e478a85 Fixed Docker link [skip ci] 2022-01-29 00:46:48 -08:00
Andrew Kane
8b301197fe Updated Homebrew tap [skip ci] 2022-01-24 16:55:28 -08:00
Andrew Kane
c02feaa9ad Updated CI 2022-01-24 16:39:01 -08:00
Andrew Kane
729374a9b8 Updated urls [skip ci] 2022-01-24 16:21:51 -08:00
Andrew Kane
a8245d6cda Updated urls [skip ci] 2022-01-24 16:16:54 -08:00
Andrew Kane
5220a6ec7e Updated DigitalOcean link [skip ci] 2022-01-23 19:10:13 -08:00
Andrew Kane
ddd873f369 Version bump to 0.2.2 [skip ci] 2022-01-15 14:23:32 -05:00
Andrew Kane
8735c4782a Fixed compilation on Mac ARM - #22 2022-01-14 01:18:33 -05:00
Andrew Kane
17ec3f3852 Moved test 2022-01-02 19:24:50 -05:00
Andrew Kane
8df12a62e7 Updated changelog [skip ci] 2022-01-02 19:20:00 -05:00
Andrew Kane
647c9002be Version bump to 0.2.1 [skip ci] 2022-01-02 19:11:37 -05:00
Andrew Kane
3e6345f02a Moved function 2022-01-02 19:09:37 -05:00
Andrew Kane
2b3484ddcd Fixed CI 2022-01-02 19:03:15 -05:00
Andrew Kane
1a6debf281 Fixed operator is not unique error - fixes #20 2022-01-02 18:47:03 -05:00
Andrew Kane
bff4d7ea68 Updated link [skip ci] 2021-10-13 14:29:09 -07:00
Andrew Kane
d5b979e4fa Added guidance on lists [skip ci] 2021-10-13 14:27:01 -07:00
Andrew Kane
d52426b3fa Improved examples [skip ci] 2021-10-13 14:06:55 -07:00
Andrew Kane
b125b2debb Added section on performance [skip ci] 2021-10-13 13:56:03 -07:00
Andrew Kane
3d7186a17c Added Docker to Makefile [skip ci] 2021-10-13 13:53:29 -07:00
Andrew Kane
58ba2139ce Added instructions for reindexing - #17 [skip ci] 2021-10-13 13:48:54 -07:00
Andrew Kane
fd93c9db86 Version bump to 0.2.0 [skip ci] 2021-10-03 20:32:45 -07:00
Andrew Kane
8dde26920c Added support for Postgres 14 2021-09-30 16:28:25 -07:00
Andrew Kane
9153a545a7 Added link to pgvector-cpp [skip ci] 2021-09-10 15:22:44 -07:00
Andrew Kane
9c20f04a11 Version bump to 0.1.8 [skip ci] 2021-09-07 14:10:58 -07:00
Andrew Kane
7c12d100ce Fixed build for Postgres < 13 2021-06-20 22:06:14 -07:00
Andrew Kane
d97d9a6561 Added cast for vector to real[] 2021-06-20 21:53:06 -07:00
Andrew Kane
f15ea301c5 Added link to Node library [skip ci] 2021-06-18 15:01:32 -07:00
Andrew Kane
cfa23f2c7a Added note on partitioning [skip ci] 2021-06-17 14:20:43 -07:00
Andrew Kane
b5b7035edc Restored section on partial indexes [skip ci] 2021-06-17 14:05:48 -07:00
Andrew Kane
478d62cdbd Added link to Go library [skip ci] 2021-06-16 17:33:49 -07:00
Andrew Kane
c7df9ef3a1 Updated changelog [skip ci] 2021-06-13 12:58:10 -07:00
67 changed files with 2219 additions and 496 deletions

View File

@@ -1,6 +1,6 @@
root = true
[*.{c,h}]
[*.{c,h,pl,pm,sql}]
indent_style = tab
indent_size = tab
tab_width = 4

View File

@@ -1,39 +1,72 @@
name: build
on: [push, pull_request]
jobs:
build:
if: "!contains(github.event.head_commit.message, '[skip ci]')"
ubuntu:
runs-on: ${{ matrix.os }}
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
postgres: [13, 12, 11, 10, 9.6]
include:
- os: macos-latest
postgres: 13
- postgres: 15
os: ubuntu-22.04
- postgres: 14
os: ubuntu-22.04
- postgres: 13
os: ubuntu-20.04
- postgres: 12
os: ubuntu-20.04
- postgres: 11
os: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: ankane/setup-postgres@v1
with:
postgres-version: ${{ matrix.postgres }}
- if: ${{ startsWith(matrix.os, 'ubuntu') }}
run: sudo apt-get update && sudo apt-get install postgresql-server-dev-${{ matrix.postgres }} libipc-run-perl
- run: make
- if: ${{ startsWith(matrix.os, 'ubuntu') }}
run: |
export PG_CONFIG=`which pg_config`
sudo --preserve-env=PG_CONFIG make install
- if: ${{ startsWith(matrix.os, 'macos') }}
run: make install
- run: make installcheck
- if: ${{ failure() }}
run: cat regression.diffs
- if: ${{ startsWith(matrix.os, 'ubuntu') }}
run: make prove_installcheck
- if: ${{ startsWith(matrix.os, 'macos') }}
run: |
brew install cpanm && cpanm IPC::Run
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_13_2.tar.gz
tar xf REL_13_2.tar.gz
make prove_installcheck PROVE=prove PERL5LIB=postgres-REL_13_2/src/test/perl
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
with:
postgres-version: ${{ matrix.postgres }}
dev-files: true
- run: make
- run: |
export PG_CONFIG=`which pg_config`
sudo --preserve-env=PG_CONFIG make install
- run: make installcheck
- if: ${{ failure() }}
run: cat regression.diffs
- run: |
sudo apt-get update
sudo apt-get install libipc-run-perl
- run: make prove_installcheck
mac:
runs-on: macos-latest
if: ${{ !startsWith(github.ref_name, 'windows') }}
steps:
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
with:
postgres-version: 14
- run: make
- run: make install
- run: make installcheck
- if: ${{ failure() }}
run: cat regression.diffs
- run: |
brew install cpanm
cpanm --notest IPC::Run
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz
tar xf REL_14_5.tar.gz
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
windows:
runs-on: windows-latest
if: ${{ !startsWith(github.ref_name, 'mac') }}
steps:
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
with:
postgres-version: 14
- run: |
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
nmake /NOLOGO /F Makefile.win && ^
nmake /NOLOGO /F Makefile.win install && ^
nmake /NOLOGO /F Makefile.win installcheck && ^
nmake /NOLOGO /F Makefile.win clean && ^
nmake /NOLOGO /F Makefile.win uninstall
shell: cmd

7
.gitignore vendored
View File

@@ -1,7 +1,14 @@
/dist/
/log/
/results/
/tmp_check/
/sql/vector--?.?.?.sql
regression.*
*.o
*.so
*.bc
*.dll
*.dylib
*.obj
*.lib
*.exp

View File

@@ -1,6 +1,84 @@
## 0.1.7 (unreleased)
## 0.4.2 (unreleased)
- Added cast for `numeric[]`
- Added notice when index created with little data
## 0.4.1 (2023-03-21)
- Improved performance of cosine distance
- Fixed index scan count
## 0.4.0 (2023-01-11)
If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgvector#040).
- Changed text representation for vector elements to match `real`
- Changed storage for vector from `plain` to `extended`
- Increased max dimensions for vector from 1024 to 16000
- Increased max dimensions for index from 1024 to 2000
- Improved accuracy of text parsing for certain inputs
- Added `avg` aggregate for vector
- Added experimental support for Windows
- Dropped support for Postgres 10
## 0.3.2 (2022-11-22)
- Fixed `invalid memory alloc request size` error
## 0.3.1 (2022-11-02)
If upgrading from 0.2.7 or 0.3.0, [recreate](https://github.com/pgvector/pgvector#031) all `ivfflat` indexes after upgrading to ensure all data is indexed.
- Fixed issue with inserts silently corrupting `ivfflat` indexes (introduced in 0.2.7)
- Fixed segmentation fault with index creation when lists > 6500
## 0.3.0 (2022-10-15)
- Added support for Postgres 15
- Dropped support for Postgres 9.6
## 0.2.7 (2022-07-31)
- Fixed `unexpected data beyond EOF` error
## 0.2.6 (2022-05-22)
- Improved performance of index creation for Postgres < 12
## 0.2.5 (2022-02-11)
- Reduced memory usage during index creation
- Fixed index creation exceeding `maintenance_work_mem`
- Fixed error with index creation when lists > 1600
## 0.2.4 (2022-02-06)
- Added support for parallel vacuum
- Fixed issue with index not reusing space
## 0.2.3 (2022-01-30)
- Added indexing progress for Postgres 12+
- Improved interrupt handling during index creation
## 0.2.2 (2022-01-15)
- Fixed compilation error on Mac ARM
## 0.2.1 (2022-01-02)
- Fixed `operator is not unique` error
## 0.2.0 (2021-10-03)
- Added support for Postgres 14
## 0.1.8 (2021-09-07)
- Added cast for `vector` to `real[]`
## 0.1.7 (2021-06-13)
- Added cast for `numeric[]` to `vector`
## 0.1.6 (2021-06-09)

View File

@@ -1,9 +1,11 @@
FROM postgres
ARG PG_MAJOR=15
FROM postgres:$PG_MAJOR
ARG PG_MAJOR
COPY . /tmp/pgvector
RUN apt-get update && \
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-13 && \
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-$PG_MAJOR && \
cd /tmp/pgvector && \
make clean && \
make OPTFLAGS="" && \
@@ -11,6 +13,6 @@ RUN apt-get update && \
mkdir /usr/share/doc/pgvector && \
cp LICENSE README.md /usr/share/doc/pgvector && \
rm -r /tmp/pgvector && \
apt-get remove -y build-essential postgresql-server-dev-13 && \
apt-get remove -y build-essential postgresql-server-dev-$PG_MAJOR && \
apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/*

View File

@@ -1,4 +1,4 @@
Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California

View File

@@ -2,7 +2,7 @@
"name": "vector",
"abstract": "Open-source vector similarity search for Postgres",
"description": "Supports L2 distance, inner product, and cosine distance",
"version": "0.1.7",
"version": "0.4.1",
"maintainer": [
"Andrew Kane <andrew@ankane.org>"
],
@@ -12,7 +12,7 @@
"prereqs": {
"runtime": {
"requires": {
"PostgreSQL": "9.6.0"
"PostgreSQL": "11.0.0"
}
}
},
@@ -20,18 +20,18 @@
"vector": {
"file": "sql/vector.sql",
"docfile": "README.md",
"version": "0.1.7",
"version": "0.4.1",
"abstract": "Open-source vector similarity search for Postgres"
}
},
"resources": {
"homepage": "https://github.com/ankane/pgvector",
"homepage": "https://github.com/pgvector/pgvector",
"bugtracker": {
"web": "https://github.com/ankane/pgvector/issues"
"web": "https://github.com/pgvector/pgvector/issues"
},
"repository": {
"url": "https://github.com/ankane/pgvector.git",
"web": "https://github.com/ankane/pgvector",
"url": "https://github.com/pgvector/pgvector.git",
"web": "https://github.com/pgvector/pgvector",
"type": "git"
}
},

View File

@@ -1,5 +1,5 @@
EXTENSION = vector
EXTVERSION = 0.1.7
EXTVERSION = 0.4.1
MODULE_big = vector
DATA = $(wildcard sql/*--*.sql)
@@ -7,14 +7,22 @@ OBJS = src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.
TESTS = $(wildcard test/sql/*.sql)
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
REGRESS_OPTS = --inputdir=test
REGRESS_OPTS = --inputdir=test --load-extension=vector
OPTFLAGS = -march=native
# Mac ARM doesn't support -march=native
ifeq ($(shell uname -s), Darwin)
ifeq ($(shell uname -p), arm)
# no difference with -march=armv8.5-a
OPTFLAGS =
endif
endif
# For auto-vectorization:
# - GCC (needs -ftree-vectorize OR -O3) - https://gcc.gnu.org/projects/tree-ssa/vectorization.html
# - Clang (could use pragma instead) - https://llvm.org/docs/Vectorizers.html
PG_CFLAGS = $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math
PG_CFLAGS += $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math
# Debug GCC auto-vectorization
# PG_CFLAGS += -fopt-info-vec
@@ -33,6 +41,14 @@ PG_CONFIG ?= pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
# for Mac
ifeq ($(PROVE),)
PROVE = prove
endif
# for Postgres 15
PROVE_FLAGS += -I ./test/perl
prove_installcheck:
rm -rf $(CURDIR)/tmp_check
cd $(srcdir) && TESTDIR='$(CURDIR)' PATH="$(bindir):$$PATH" PGPORT='6$(DEF_PGPORT)' PG_REGRESS='$(top_builddir)/src/test/regress/pg_regress' $(PROVE) $(PG_PROVE_FLAGS) $(PROVE_FLAGS) $(if $(PROVE_TESTS),$(PROVE_TESTS),test/t/*.pl)
@@ -42,3 +58,8 @@ prove_installcheck:
dist:
mkdir -p dist
git archive --format zip --prefix=$(EXTENSION)-$(EXTVERSION)/ --output dist/$(EXTENSION)-$(EXTVERSION).zip master
.PHONY: docker
docker:
docker build --pull --no-cache --platform linux/amd64 -t ankane/pgvector:latest .

70
Makefile.win Normal file
View File

@@ -0,0 +1,70 @@
EXTENSION = vector
EXTVERSION = 0.4.1
OBJS = src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
REGRESS_OPTS = --inputdir=test --load-extension=vector
# For /arch flags
# https://learn.microsoft.com/en-us/cpp/build/reference/arch-minimum-cpu-architecture
OPTFLAGS =
# For auto-vectorization:
# - MSVC (needs /O2 /fp:fast) - https://learn.microsoft.com/en-us/cpp/parallel/auto-parallelization-and-auto-vectorization?#auto-vectorizer
PG_CFLAGS = $(PG_CFLAGS) $(OPTFLAGS) /O2 /fp:fast
# Debug MSVC auto-vectorization
# https://learn.microsoft.com/en-us/cpp/error-messages/tool-errors/vectorizer-and-parallelizer-messages
# PG_CFLAGS = $(PG_CFLAGS) /Qvec-report:2
all: sql\$(EXTENSION)--$(EXTVERSION).sql
sql\$(EXTENSION)--$(EXTVERSION).sql: sql\$(EXTENSION).sql
copy sql\$(EXTENSION).sql $@
# TODO use pg_config
!ifndef PGROOT
!error PGROOT is not set
!endif
BINDIR = $(PGROOT)\bin
INCLUDEDIR = $(PGROOT)\include
INCLUDEDIR_SERVER = $(PGROOT)\include\server
LIBDIR = $(PGROOT)\lib
PKGLIBDIR = $(PGROOT)\lib
SHAREDIR = $(PGROOT)\share
CFLAGS = /nologo /I"$(INCLUDEDIR_SERVER)\port\win32_msvc" /I"$(INCLUDEDIR_SERVER)\port\win32" /I"$(INCLUDEDIR_SERVER)" /I"$(INCLUDEDIR)"
CFLAGS = $(CFLAGS) $(PG_CFLAGS)
SHLIB = $(EXTENSION).dll
LIBS = "$(LIBDIR)\postgres.lib"
.c.obj:
$(CC) $(CFLAGS) /c $< /Fo$@
$(SHLIB): $(OBJS)
$(CC) $(CFLAGS) $(OBJS) $(LIBS) /link /DLL /OUT:$(SHLIB)
all: $(SHLIB)
install:
copy $(SHLIB) "$(PKGLIBDIR)"
copy $(EXTENSION).control "$(SHAREDIR)\extension"
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
installcheck:
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
uninstall:
del /f "$(PKGLIBDIR)\$(SHLIB)"
del /f "$(SHAREDIR)\extension\$(EXTENSION).control"
del /f "$(SHAREDIR)\extension\vector--*.sql"
clean:
del /f $(SHLIB) $(EXTENSION).lib $(EXTENSION).exp
del /f $(OBJS)
del /f sql\$(EXTENSION)--$(EXTVERSION).sql
del /f /s /q results regression.diffs regression.out tmp_check tmp_check_iso log output_iso

404
README.md
View File

@@ -2,22 +2,17 @@
Open-source vector similarity search for Postgres
```sql
CREATE TABLE table (column vector(3));
CREATE INDEX ON table USING ivfflat (column);
SELECT * FROM table ORDER BY column <-> '[1,2,3]' LIMIT 5;
```
Supports exact and approximate nearest neighbor search for L2 distance, inner product, and cosine distance
Supports L2 distance, inner product, and cosine distance
[![Build Status](https://github.com/ankane/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/ankane/pgvector/actions)
[![Build Status](https://github.com/pgvector/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/pgvector/pgvector/actions)
## Installation
Compile and install the extension (supports Postgres 9.6+)
Compile and install the extension (supports Postgres 11+)
```sh
git clone --branch v0.1.7 https://github.com/ankane/pgvector.git
cd /tmp
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector
make
make install # may need sudo
@@ -29,88 +24,292 @@ Then load it in databases where you want to use it
CREATE EXTENSION vector;
```
You can also install it with [Docker](#docker), [Homebrew](#homebrew), or [PGXN](#pgxn)
See the [installation notes](#installation-notes) if you run into issues
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [Yum](#yum), or [conda-forge](#conda-forge)
## Getting Started
Create a vector column with 3 dimensions (replace `table` and `column` with non-reserved names)
Create a vector column with 3 dimensions
```sql
CREATE TABLE table (column vector(3));
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
```
Insert values
```sql
INSERT INTO table VALUES ('[1,2,3]'), ('[4,5,6]');
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
```
Get the nearest neighbor by L2 distance
Get the nearest neighbors by L2 distance
```sql
SELECT * FROM table ORDER BY column <-> '[3,1,2]' LIMIT 1;
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
Also supports inner product (`<#>`) and cosine distance (`<=>`)
Note: `<#>` returns the negative inner product since Postgres only supports `ASC` order index scans on operators
## Storing
Create a new table with a vector column
```sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
```
Or add a vector column to an existing table
```sql
ALTER TABLE items ADD COLUMN embedding vector(3);
```
Insert vectors
```sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
```
Upsert vectors
```sql
INSERT INTO items (id, embedding) VALUES (1, '[1,2,3]'), (2, '[4,5,6]')
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
```
Update vectors
```sql
UPDATE items SET embedding = '[1,2,3]' WHERE id = 1;
```
Delete vectors
```sql
DELETE FROM items WHERE id = 1;
```
## Querying
Get the nearest neighbors to a vector
```sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
Get the nearest neighbors to a row
```sql
SELECT * FROM items WHERE id != 1 ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1) LIMIT 5;
```
Get rows within a certain distance
```sql
SELECT * FROM items WHERE embedding <-> '[3,1,2]' < 5;
```
Note: Combine with `ORDER BY` and `LIMIT` to use an index
#### Distances
Get the distance
```sql
SELECT embedding <-> '[3,1,2]' AS distance FROM items;
```
For inner product, multiply by -1 (since `<#>` returns the negative inner product)
```sql
SELECT -1 * (embedding <#> '[3,1,2]') AS inner_product FROM items;
```
For cosine similarity, use 1 - cosine distance
```sql
SELECT 1 - (embedding <=> '[3,1,2]') AS cosine_similarity FROM items;
```
#### Averaging
Average vectors
```sql
SELECT AVG(embedding) FROM items;
```
Average groups of vectors
```sql
SELECT category_id, AVG(embedding) FROM items GROUP BY category_id;
```
## Indexing
Speed up queries with an approximate index. Add an index for each distance function you want to use.
By default, pgvector performs exact nearest neighbor search, which provides perfect recall.
You can add an index to use approximate nearest neighbor search, which trades some recall for performance. Unlike typical indexes, you will see different results for queries after adding an approximate index.
Three keys to achieving good recall are:
1. Create the index *after* the table has some data
2. Choose an appropriate number of lists (a good place to start is `rows / 1000` for up to 1M rows and `sqrt(rows)` for over 1M rows)
3. When querying, specify an appropriate number of [probes](#query-options) (higher is better for recall, lower is better for speed)
Add an index for each distance function you want to use.
L2 distance
```sql
CREATE INDEX ON table USING ivfflat (column);
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
```
Inner product
```sql
CREATE INDEX ON table USING ivfflat (column vector_ip_ops);
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100);
```
Cosine distance
```sql
CREATE INDEX ON table USING ivfflat (column vector_cosine_ops);
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
```
Indexes should be created after the table has data for optimal clustering. Also, unlike typical indexes which only affect performance, you may see different results for queries after adding an approximate index.
### Index Options
Specify the number of inverted lists (100 by default)
```sql
CREATE INDEX ON table USING ivfflat (column) WITH (lists = 100);
```
Vectors with up to 2,000 dimensions can be indexed.
### Query Options
Specify the number of probes (1 by default)
```sql
SET ivfflat.probes = 1;
SET ivfflat.probes = 10;
```
A higher value improves recall at the cost of speed.
A higher value provides better recall at the cost of speed, and it can be set to the number of lists for exact nearest neighbor search (at which point the planner wont use the index)
Use `SET LOCAL` inside a transaction to set it for a single query
```sql
BEGIN;
SET LOCAL ivfflat.probes = 1;
SET LOCAL ivfflat.probes = 10;
SELECT ...
COMMIT;
```
### Indexing Progress
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
```sql
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
```
The phases are:
1. `initializing`
2. `performing k-means`
3. `sorting tuples`
4. `loading tuples`
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
### Partial Indexes
Consider [partial indexes](https://www.postgresql.org/docs/current/indexes-partial.html) for queries with a `WHERE` clause
```sql
SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
can be indexed with:
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100) WHERE (category_id = 123);
```
To index many different values of `category_id`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `category_id`.
```sql
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
```
## Performance
Use `EXPLAIN ANALYZE` to debug performance.
```sql
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
### Exact Search
To speed up queries without an index, increase `max_parallel_workers_per_gather`.
```sql
SET max_parallel_workers_per_gather = 4;
```
If vectors are normalized to length 1 (like [OpenAI embeddings](https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use)), use inner product for best performance.
```sql
SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
```
### Approximate Search
To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
```
## Languages
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
Language | Libraries / Examples
--- | ---
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
C# | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
Java, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
Node.js | [pgvector-node](https://github.com/pgvector/pgvector-node)
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
R | [pgvector-r](https://github.com/pgvector/pgvector-r)
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
## Frequently Asked Questions
#### How many vectors can be stored in a single table?
A non-partitioned table has a limit of 32 TB by default in Postgres. A partitioned table can have thousands of partitions of that size.
#### Is replication supported?
Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
#### What if I want to index vectors with more than 2,000 dimensions?
Two things you can try are:
1. use dimensionality reduction
2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/ivfflat.h`
## Reference
### Vector Type
Each vector takes `4 * dimensions + 8` bytes of storage. Each element is a float, and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Vectors can have up to 1024 dimensions.
Each vector takes `4 * dimensions + 8` bytes of storage. Each element is a single precision floating-point number (like the `real` type in Postgres), and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Vectors can have up to 16,000 dimensions.
### Vector Operators
@@ -126,46 +325,80 @@ Operator | Description
Function | Description
--- | ---
cosine_distance(vector, vector) | cosine distance
inner_product(vector, vector) | inner product
l2_distance(vector, vector) | Euclidean distance
vector_dims(vector) | number of dimensions
vector_norm(vector) | Euclidean norm
cosine_distance(vector, vector) → double precision | cosine distance
inner_product(vector, vector) → double precision | inner product
l2_distance(vector, vector) → double precision | Euclidean distance
vector_dims(vector) → integer | number of dimensions
vector_norm(vector) → double precision | Euclidean norm
## Libraries
### Aggregate Functions
Libraries that use pgvector:
Function | Description
--- | ---
avg(vector) → vector | arithmetic mean
- [pgvector-python](https://github.com/ankane/pgvector-python) (Python)
- [Neighbor](https://github.com/ankane/neighbor) (Ruby)
- [pgvector-rust](https://github.com/ankane/pgvector-rust) (Rust)
## Installation Notes
### Postgres Location
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
```sh
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
```
Then re-run the installation instructions (run `make clean` before `make` if needed)
### Missing Header
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
For Ubuntu and Debian, use:
```sh
sudo apt-get install postgresql-server-dev-15
```
Note: Replace `15` with your Postgres server version
### Windows
Support for Windows is currently experimental. Use `nmake` to build:
```cmd
set "PGROOT=C:\Program Files\PostgreSQL\15"
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector
nmake /F Makefile.win
nmake /F Makefile.win install
```
## Additional Installation Methods
### Docker
Get the [Docker image](https://hub.docker.com/repository/docker/ankane/pgvector) with:
Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
```sh
docker pull ankane/pgvector
```
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres).
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (run it the same way).
You can also build the image manually
You can also build the image manually:
```sh
git clone --branch v0.1.7 https://github.com/ankane/pgvector.git
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector
docker build -t pgvector .
```
### Homebrew
On Mac with Homebrew Postgres, you can use:
With Homebrew Postgres, you can use:
```sh
brew install ankane/brew/pgvector
brew install pgvector
```
### PGXN
@@ -176,14 +409,39 @@ Install from the [PostgreSQL Extension Network](https://pgxn.org/dist/vector) wi
pgxn install vector
```
### Yum
RPM packages are available from the [PostgreSQL Yum Repository](https://yum.postgresql.org/). Follow the [setup instructions](https://www.postgresql.org/download/linux/redhat/) for your distribution and run:
```sh
sudo yum install pgvector_15
# or
sudo dnf install pgvector_15
```
Note: Replace `15` with your Postgres server version
### conda-forge
With Conda Postgres, install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with:
```sh
conda install -c conda-forge pgvector
```
This method is [community-maintained](https://github.com/conda-forge/pgvector-feedstock) by [@mmcauliffe](https://github.com/mmcauliffe)
## Hosted Postgres
Some Postgres providers only support specific extensions. To request a new extension:
pgvector is available on [these providers](https://github.com/pgvector/pgvector/issues/54).
To request a new extension on other providers:
- Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/)
- Google Cloud SQL - follow the instructions on [this page](https://cloud.google.com/sql/docs/postgres/extensions#requesting-support-for-a-new-extension)
- DigitalOcean Managed Databases - follow the instructions on [this page](https://docs.digitalocean.com/products/databases/postgresql/resources/supported-extensions/#supported-extensions)
- Azure Database for PostgreSQL - follow the instructions on [this page](https://docs.microsoft.com/en-us/azure/postgresql/concepts-extensions#next-steps)
- Google Cloud SQL - vote or comment on [this page](https://issuetracker.google.com/issues/265172065)
- Azure Database - vote or comment on [this page](https://feedback.azure.com/d365community/idea/7b423322-6189-ed11-a81b-000d3ae49307)
- DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql)
- Render - vote or comment on [this page](https://feedback.render.com/features/p/add-pgvector-extension-to-postgresql)
## Upgrading
@@ -193,6 +451,32 @@ Install the latest version and run:
ALTER EXTENSION vector UPDATE;
```
## Upgrade Notes
### 0.4.0
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
```sql
ALTER TYPE vector SET (STORAGE = extended);
```
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
### 0.3.1
If upgrading from 0.2.7 or 0.3.0, recreate all `ivfflat` indexes after upgrading to ensure all data is indexed.
```sql
-- Postgres 12+
REINDEX INDEX CONCURRENTLY index_name;
-- Postgres < 12
CREATE INDEX CONCURRENTLY temp_name ON table USING ivfflat (column opclass);
DROP INDEX CONCURRENTLY index_name;
ALTER INDEX temp_name RENAME TO index_name;
```
## Thanks
Thanks to:
@@ -205,21 +489,21 @@ Thanks to:
## History
View the [changelog](https://github.com/ankane/pgvector/blob/master/CHANGELOG.md)
View the [changelog](https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md)
## Contributing
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- [Report bugs](https://github.com/ankane/pgvector/issues)
- Fix bugs and [submit pull requests](https://github.com/ankane/pgvector/pulls)
- [Report bugs](https://github.com/pgvector/pgvector/issues)
- Fix bugs and [submit pull requests](https://github.com/pgvector/pgvector/pulls)
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
```sh
git clone https://github.com/ankane/pgvector.git
git clone https://github.com/pgvector/pgvector.git
cd pgvector
make
make install
@@ -239,6 +523,12 @@ make installcheck REGRESS=functions # regression test
make prove_installcheck PROVE_TESTS=test/t/001_wal.pl # TAP test
```
To enable benchmarking:
```sh
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
```
Resources for contributors
- [Extension Building Infrastructure](https://www.postgresql.org/docs/current/extend-pgxs.html)

View File

@@ -0,0 +1,8 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.1.8'" to load this file. \quit
CREATE FUNCTION vector_to_float4(vector, integer, boolean) RETURNS real[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE CAST (vector AS real[])
WITH FUNCTION vector_to_float4(vector, integer, boolean) AS IMPLICIT;

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.0'" to load this file. \quit

View File

@@ -0,0 +1,19 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.1'" to load this file. \quit
DROP CAST (integer[] AS vector);
DROP CAST (real[] AS vector);
DROP CAST (double precision[] AS vector);
DROP CAST (numeric[] AS vector);
CREATE CAST (integer[] AS vector)
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (real[] AS vector)
WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (double precision[] AS vector)
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (numeric[] AS vector)
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.2'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.3'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.4'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.5'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.6'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.7'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.3.0'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.3.1'" to load this file. \quit

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.3.2'" to load this file. \quit

View File

@@ -0,0 +1,23 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.4.0'" to load this file. \quit
-- remove this single line for Postgres < 13
ALTER TYPE vector SET (STORAGE = extended);
CREATE FUNCTION vector_accum(double precision[], vector) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE AGGREGATE avg(vector) (
SFUNC = vector_accum,
STYPE = double precision[],
FINALFUNC = vector_avg,
COMBINEFUNC = vector_combine,
INITCOND = '{0}',
PARALLEL = SAFE
);

View File

@@ -0,0 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.4.1'" to load this file. \quit

View File

@@ -25,7 +25,8 @@ CREATE TYPE vector (
OUTPUT = vector_out,
TYPMOD_IN = vector_typmod_in,
RECEIVE = vector_recv,
SEND = vector_send
SEND = vector_send,
STORAGE = extended
);
-- functions
@@ -83,6 +84,26 @@ CREATE FUNCTION vector_negative_inner_product(vector, vector) RETURNS float8
CREATE FUNCTION vector_spherical_distance(vector, vector) RETURNS float8
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_accum(double precision[], vector) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
-- aggregates
CREATE AGGREGATE avg(vector) (
SFUNC = vector_accum,
STYPE = double precision[],
FINALFUNC = vector_avg,
COMBINEFUNC = vector_combine,
INITCOND = '{0}',
PARALLEL = SAFE
);
-- cast functions
CREATE FUNCTION vector(vector, integer, boolean) RETURNS vector
@@ -100,22 +121,28 @@ CREATE FUNCTION array_to_vector(double precision[], integer, boolean) RETURNS ve
CREATE FUNCTION array_to_vector(numeric[], integer, boolean) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_to_float4(vector, integer, boolean) RETURNS real[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
-- casts
CREATE CAST (vector AS vector)
WITH FUNCTION vector(vector, integer, boolean) AS IMPLICIT;
CREATE CAST (vector AS real[])
WITH FUNCTION vector_to_float4(vector, integer, boolean) AS IMPLICIT;
CREATE CAST (integer[] AS vector)
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS IMPLICIT;
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (real[] AS vector)
WITH FUNCTION array_to_vector(real[], integer, boolean) AS IMPLICIT;
WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (double precision[] AS vector)
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS IMPLICIT;
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (numeric[] AS vector)
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS IMPLICIT;
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;
-- operators

View File

@@ -6,18 +6,25 @@
#include "ivfflat.h"
#include "miscadmin.h"
#include "storage/bufmgr.h"
#include "utils/memutils.h"
#if PG_VERSION_NUM >= 140000
#include "utils/backend_progress.h"
#elif PG_VERSION_NUM >= 120000
#include "pgstat.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "access/tableam.h"
#include "commands/progress.h"
#else
#define PROGRESS_CREATEIDX_SUBPHASE 0
#define PROGRESS_CREATEIDX_TUPLES_TOTAL 0
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
#endif
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_d.h"
#include "catalog/pg_type_d.h"
#else
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#endif
#if PG_VERSION_NUM >= 130000
#define CALLBACK_ITEM_POINTER ItemPointer tid
@@ -25,21 +32,23 @@
#define CALLBACK_ITEM_POINTER HeapTuple hup
#endif
#if PG_VERSION_NUM >= 120000
#define UpdateProgress(index, val) pgstat_progress_update_param(index, val)
#else
#define UpdateProgress(index, val) ((void)val)
#endif
/*
* Callback for sampling
* Add sample
*/
static void
SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
AddSample(Datum *values, IvfflatBuildState * buildstate)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
VectorArray samples = buildstate->samples;
int targsamples = samples->maxlen;
Datum value = values[0];
/* Skip nulls */
if (isnull[0])
return;
/* Detoast once for all calls */
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/*
* Normalize with KMEANS_NORM_PROC since spherical distance function
@@ -63,7 +72,11 @@ SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
if (buildstate->rowstoskip <= 0)
{
#if PG_VERSION_NUM >= 150000
int k = (int) (targsamples * sampler_random_fract(&buildstate->rstate.randstate));
#else
int k = (int) (targsamples * sampler_random_fract(buildstate->rstate.randstate));
#endif
Assert(k >= 0 && k < targsamples);
VectorArraySet(samples, k, DatumGetVector(value));
@@ -73,6 +86,31 @@ SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
}
}
/*
* Callback for sampling
*/
static void
SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
MemoryContext oldCtx;
/* Skip nulls */
if (isnull[0])
return;
/* Use memory context since detoast can allocate */
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
/* Add sample */
AddSample(values, state);
/* Reset memory context */
MemoryContextSwitchTo(oldCtx);
MemoryContextReset(buildstate->tmpCtx);
}
/*
* Sample rows with same logic as ANALYZE
*/
@@ -84,7 +122,7 @@ SampleRows(IvfflatBuildState * buildstate)
buildstate->rowstoskip = -1;
BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, random());
BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, RandomInt());
reservoir_init_selection_state(&buildstate->rstate, targsamples);
while (BlockSampler_HasMore(&buildstate->bs))
@@ -93,39 +131,29 @@ SampleRows(IvfflatBuildState * buildstate)
#if PG_VERSION_NUM >= 120000
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#elif PG_VERSION_NUM >= 110000
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#else
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, true, targblock, 1, SampleCallback, (void *) buildstate);
false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#endif
}
}
/*
* Callback for table_index_build_scan
* Add tuple to sort
*/
static void
BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState * buildstate)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
double distance;
double minDistance = DBL_MAX;
int closestCenter = -1;
VectorArray centers = buildstate->centers;
TupleTableSlot *slot = buildstate->slot;
Datum value = values[0];
int i;
#if PG_VERSION_NUM < 130000
ItemPointer tid = &hup->t_self;
#endif
if (isnull[0])
return;
/* Detoast once for all calls */
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/* Normalize if needed */
if (buildstate->normprocinfo != NULL)
@@ -146,16 +174,20 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
}
}
#ifdef IVFFLAT_KMEANS_DEBUG
buildstate->inertia += minDistance;
buildstate->listSums[closestCenter] += minDistance;
buildstate->listCounts[closestCenter]++;
#endif
/* Create a virtual tuple */
ExecClearTuple(slot);
slot->tts_values[0] = Int32GetDatum(closestCenter);
slot->tts_isnull[0] = false;
slot->tts_values[1] = Int32GetDatum(ItemPointerGetBlockNumberNoCheck(tid));
slot->tts_values[1] = PointerGetDatum(tid);
slot->tts_isnull[1] = false;
slot->tts_values[2] = Int32GetDatum(ItemPointerGetOffsetNumberNoCheck(tid));
slot->tts_values[2] = value;
slot->tts_isnull[2] = false;
slot->tts_values[3] = value;
slot->tts_isnull[3] = false;
ExecStoreVirtualTuple(slot);
/*
@@ -165,6 +197,37 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
* need not save it.
*/
tuplesort_puttupleslot(buildstate->sortstate, slot);
buildstate->indtuples++;
}
/*
* Callback for table_index_build_scan
*/
static void
BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
MemoryContext oldCtx;
#if PG_VERSION_NUM < 130000
ItemPointer tid = &hup->t_self;
#endif
/* Skip nulls */
if (isnull[0])
return;
/* Use memory context since detoast can allocate */
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
/* Add tuple to sort */
AddTupleToSort(index, tid, values, buildstate);
/* Reset memory context */
MemoryContextSwitchTo(oldCtx);
MemoryContextReset(buildstate->tmpCtx);
}
/*
@@ -175,23 +238,15 @@ GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot,
{
Datum value;
bool isnull;
int tupblk;
int tupoff;
#if PG_VERSION_NUM >= 100000
if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL))
#else
if (tuplesort_gettupleslot(sortstate, true, slot, NULL))
#endif
{
*list = DatumGetInt32(slot_getattr(slot, 1, &isnull));
tupblk = DatumGetInt32(slot_getattr(slot, 2, &isnull));
tupoff = DatumGetInt32(slot_getattr(slot, 3, &isnull));
value = slot_getattr(slot, 4, &isnull);
value = slot_getattr(slot, 3, &isnull);
/* Form the index tuple */
*itup = index_form_tuple(tupdesc, &value, &isnull);
ItemPointerSet(&(*itup)->t_tid, tupblk, tupoff);
(*itup)->t_tid = *((ItemPointer) DatumGetPointer(slot_getattr(slot, 2, &isnull)));
}
else
*list = -1;
@@ -208,10 +263,11 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
GenericXLogState *state;
int list;
IndexTuple itup = NULL; /* silence compiler warning */
BlockNumber startPage = InvalidBlockNumber;
BlockNumber insertPage = InvalidBlockNumber;
BlockNumber startPage;
BlockNumber insertPage;
Size itemsz;
int i;
int64 inserted = 0;
#if PG_VERSION_NUM >= 120000
TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsMinimalTuple);
@@ -220,12 +276,20 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
#endif
TupleDesc tupdesc = RelationGetDescr(index);
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
for (i = 0; i < buildstate->centers->length; i++)
{
/* Can take a while, so ensure we can interrupt */
/* Needs to be called when no buffer locks are held */
CHECK_FOR_INTERRUPTS();
buf = IvfflatNewBuffer(index, forkNum);
IvfflatInitPage(index, &buf, &page, &state);
IvfflatInitRegisterPage(index, &buf, &page, &state);
startPage = BufferGetBlockNumber(buf);
@@ -243,7 +307,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
pfree(itup);
buildstate->indtuples += 1;
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
}
@@ -253,7 +317,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
IvfflatCommitBuffer(buf, state);
/* Set the start and insert pages */
IvfflatUpdateList(index, state, buildstate->listInfo[i], insertPage, startPage, forkNum);
IvfflatUpdateList(index, state, buildstate->listInfo[i], insertPage, InvalidBlockNumber, startPage, forkNum);
}
}
@@ -274,6 +338,9 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
if (buildstate->dimensions < 0)
elog(ERROR, "column does not have dimensions");
if (buildstate->dimensions > IVFFLAT_MAX_DIM)
elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", IVFFLAT_MAX_DIM);
buildstate->reltuples = 0;
buildstate->indtuples = 0;
@@ -283,20 +350,21 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
buildstate->kmeansnormprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
buildstate->collation = index->rd_indcollation[0];
/* Require more than one dimension for spherical k-means */
/* Lists check for backwards compatibility */
/* TODO Remove lists check in 0.3.0 */
if (buildstate->kmeansnormprocinfo != NULL && buildstate->dimensions == 1 && buildstate->lists > 1)
elog(ERROR, "dimensions must be greater than one for this opclass");
/* Create tuple description for sorting */
#if PG_VERSION_NUM >= 120000
buildstate->tupdesc = CreateTemplateTupleDesc(4);
buildstate->tupdesc = CreateTemplateTupleDesc(3);
#else
buildstate->tupdesc = CreateTemplateTupleDesc(4, false);
buildstate->tupdesc = CreateTemplateTupleDesc(3, false);
#endif
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "blkno", INT4OID, -1, 0);
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "offset", INT4OID, -1, 0);
#if PG_VERSION_NUM >= 110000
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 4, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0);
#else
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 4, "vector", RelationGetDescr(index)->attrs[0]->atttypid, -1, 0);
#endif
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0);
#if PG_VERSION_NUM >= 120000
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
@@ -309,6 +377,16 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
/* Reuse for each tuple */
buildstate->normvec = InitVector(buildstate->dimensions);
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
"Ivfflat build temporary context",
ALLOCSET_DEFAULT_SIZES);
#ifdef IVFFLAT_KMEANS_DEBUG
buildstate->inertia = 0;
buildstate->listSums = palloc0(sizeof(double) * buildstate->lists);
buildstate->listCounts = palloc0(sizeof(int) * buildstate->lists);
#endif
}
/*
@@ -317,9 +395,16 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
static void
FreeBuildState(IvfflatBuildState * buildstate)
{
pfree(buildstate->centers);
VectorArrayFree(buildstate->centers);
pfree(buildstate->listInfo);
pfree(buildstate->normvec);
#ifdef IVFFLAT_KMEANS_DEBUG
pfree(buildstate->listSums);
pfree(buildstate->listCounts);
#endif
MemoryContextDelete(buildstate->tmpCtx);
}
/*
@@ -330,22 +415,39 @@ ComputeCenters(IvfflatBuildState * buildstate)
{
int numSamples;
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
/* Target 50 samples per list, with at least 10000 samples */
/* The number of samples has a large effect on index build time */
numSamples = buildstate->lists * 50;
if (numSamples < 10000)
numSamples = 10000;
/* Sample samples */
/* Skip samples for unlogged table */
if (buildstate->heap == NULL)
numSamples = 1;
/* Sample rows */
/* TODO Ensure within maintenance_work_mem */
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions);
if (buildstate->heap != NULL)
{
SampleRows(buildstate);
if (buildstate->samples->length < buildstate->lists)
{
ereport(NOTICE,
(errmsg("ivfflat index created with little data"),
errdetail("this will cause poor recall"),
errhint("drop the index until the table has more data")));
}
}
/* Calculate centers */
IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers);
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers));
/* Free samples before we allocate more memory */
pfree(buildstate->samples);
VectorArrayFree(buildstate->samples);
}
/*
@@ -360,7 +462,7 @@ CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
IvfflatMetaPage metap;
buf = IvfflatNewBuffer(index, forkNum);
IvfflatInitPage(index, &buf, &page, &state);
IvfflatInitRegisterPage(index, &buf, &page, &state);
/* Set metapage data */
metap = IvfflatPageGetMeta(page);
@@ -393,7 +495,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
list = palloc(itemsz);
buf = IvfflatNewBuffer(index, forkNum);
IvfflatInitPage(index, &buf, &page, &state);
IvfflatInitRegisterPage(index, &buf, &page, &state);
for (i = 0; i < lists; i++)
{
@@ -421,6 +523,51 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
pfree(list);
}
/*
* Print k-means metrics
*/
#ifdef IVFFLAT_KMEANS_DEBUG
static void
PrintKmeansMetrics(IvfflatBuildState * buildstate)
{
elog(INFO, "inertia: %.3e", buildstate->inertia);
/* Calculate Davies-Bouldin index */
if (buildstate->lists > 1)
{
double db = 0.0;
/* Calculate average distance */
for (int i = 0; i < buildstate->lists; i++)
{
if (buildstate->listCounts[i] > 0)
buildstate->listSums[i] /= buildstate->listCounts[i];
}
for (int i = 0; i < buildstate->lists; i++)
{
double max = 0.0;
double distance;
for (int j = 0; j < buildstate->lists; j++)
{
if (j == i)
continue;
distance = DatumGetFloat8(FunctionCall2Coll(buildstate->procinfo, buildstate->collation, PointerGetDatum(VectorArrayGet(buildstate->centers, i)), PointerGetDatum(VectorArrayGet(buildstate->centers, j))));
distance = (buildstate->listSums[i] + buildstate->listSums[j]) / distance;
if (distance > max)
max = distance;
}
db += max;
}
db /= buildstate->lists;
elog(INFO, "davies-bouldin: %.3f", db);
}
}
#endif
/*
* Create entry pages
*/
@@ -432,11 +579,9 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
Oid sortCollations[] = {InvalidOid};
bool nullsFirstFlags[] = {false};
#if PG_VERSION_NUM >= 110000
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_SORT);
buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, NULL, false);
#else
buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, false);
#endif
/* Add tuples to sort */
if (buildstate->heap != NULL)
@@ -444,17 +589,20 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
#if PG_VERSION_NUM >= 120000
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, true, BuildCallback, (void *) buildstate, NULL);
#elif PG_VERSION_NUM >= 110000
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate, NULL);
#else
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate);
true, BuildCallback, (void *) buildstate, NULL);
#endif
}
/* Sort and insert */
/* Sort */
tuplesort_performsort(buildstate->sortstate);
#ifdef IVFFLAT_KMEANS_DEBUG
PrintKmeansMetrics(buildstate);
#endif
/* Insert */
InsertTuples(buildstate->index, buildstate, forkNum);
tuplesort_end(buildstate->sortstate);
}
@@ -473,7 +621,7 @@ BuildIndex(Relation heap, Relation index, IndexInfo *indexInfo,
/* Create pages */
CreateMetaPage(index, buildstate->dimensions, buildstate->lists, forkNum);
CreateListPages(index, buildstate->centers, buildstate->dimensions, buildstate->lists, forkNum, &buildstate->listInfo);
CreateEntryPages(buildstate, forkNum);
IvfflatBench("CreateEntryPages", CreateEntryPages(buildstate, forkNum));
FreeBuildState(buildstate);
}

View File

@@ -8,6 +8,10 @@
#include "utils/guc.h"
#include "utils/selfuncs.h"
#if PG_VERSION_NUM >= 120000
#include "commands/progress.h"
#endif
int ivfflat_probes;
static relopt_kind ivfflat_relopt_kind;
@@ -30,6 +34,29 @@ _PG_init(void)
1, 1, IVFFLAT_MAX_LISTS, PGC_USERSET, 0, NULL, NULL, NULL);
}
/*
* Get the name of index build phase
*/
#if PG_VERSION_NUM >= 120000
static char *
ivfflatbuildphasename(int64 phasenum)
{
switch (phasenum)
{
case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
return "initializing";
case PROGRESS_IVFFLAT_PHASE_KMEANS:
return "performing k-means";
case PROGRESS_IVFFLAT_PHASE_SORT:
return "sorting tuples";
case PROGRESS_IVFFLAT_PHASE_LOAD:
return "loading tuples";
default:
return NULL;
}
}
#endif
/*
* Estimate the cost of an index scan
*/
@@ -37,9 +64,7 @@ static void
ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
Cost *indexStartupCost, Cost *indexTotalCost,
Selectivity *indexSelectivity, double *indexCorrelation
#if PG_VERSION_NUM >= 100000
,double *indexPages
#endif
)
{
GenericCosts costs;
@@ -57,9 +82,7 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
*indexTotalCost = DBL_MAX;
*indexSelectivity = 0;
*indexCorrelation = 0;
#if PG_VERSION_NUM >= 100000
*indexPages = 0;
#endif
return;
}
@@ -87,9 +110,7 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
*indexTotalCost = costs.indexTotalCost;
*indexSelectivity = costs.indexSelectivity;
*indexCorrelation = costs.indexCorrelation;
#if PG_VERSION_NUM >= 100000
*indexPages = costs.numIndexPages;
#endif
}
/*
@@ -130,7 +151,12 @@ ivfflatvalidate(Oid opclassoid)
return true;
}
PG_FUNCTION_INFO_V1(ivfflathandler);
/*
* Define index handler
*
* See https://www.postgresql.org/docs/current/index-api.html
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(ivfflathandler);
Datum
ivfflathandler(PG_FUNCTION_ARGS)
{
@@ -152,31 +178,31 @@ ivfflathandler(PG_FUNCTION_ARGS)
amroutine->amstorage = false;
amroutine->amclusterable = false;
amroutine->ampredlocks = false;
#if PG_VERSION_NUM >= 100000
amroutine->amcanparallel = false;
#endif
#if PG_VERSION_NUM >= 110000
amroutine->amcaninclude = false;
#endif
#if PG_VERSION_NUM >= 130000
amroutine->amusemaintenanceworkmem = false; /* not used during VACUUM */
amroutine->amparallelvacuumoptions = VACUUM_OPTION_NO_PARALLEL; /* TODO support parallel */
amroutine->amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL;
#endif
amroutine->amkeytype = InvalidOid;
/* Interface functions */
amroutine->ambuild = ivfflatbuild;
amroutine->ambuildempty = ivfflatbuildempty;
amroutine->aminsert = ivfflatinsert;
amroutine->ambulkdelete = ivfflatbulkdelete;
amroutine->amvacuumcleanup = ivfflatvacuumcleanup;
amroutine->amcanreturn = NULL;
amroutine->amcanreturn = NULL; /* tuple not included in heapsort */
amroutine->amcostestimate = ivfflatcostestimate;
amroutine->amoptions = ivfflatoptions;
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
#if PG_VERSION_NUM >= 120000
amroutine->ambuildphasename = NULL;
amroutine->ambuildphasename = ivfflatbuildphasename;
#endif
amroutine->amvalidate = ivfflatvalidate;
#if PG_VERSION_NUM >= 140000
amroutine->amadjustmembers = NULL;
#endif
amroutine->ambeginscan = ivfflatbeginscan;
amroutine->amrescan = ivfflatrescan;
amroutine->amgettuple = ivfflatgettuple;
@@ -184,11 +210,11 @@ ivfflathandler(PG_FUNCTION_ARGS)
amroutine->amendscan = ivfflatendscan;
amroutine->ammarkpos = NULL;
amroutine->amrestrpos = NULL;
#if PG_VERSION_NUM >= 100000
/* Interface functions to support parallel index scans */
amroutine->amestimateparallelscan = NULL;
amroutine->aminitparallelscan = NULL;
amroutine->amparallelrescan = NULL;
#endif
PG_RETURN_POINTER(amroutine);
}

View File

@@ -3,13 +3,28 @@
#include "postgres.h"
#if PG_VERSION_NUM < 110000
#error "Requires PostgreSQL 11+"
#endif
#include "access/generic_xlog.h"
#include "access/reloptions.h"
#include "nodes/execnodes.h"
#include "port.h" /* for strtof() and random() */
#include "utils/sampling.h"
#include "utils/tuplesort.h"
#include "vector.h"
#if PG_VERSION_NUM >= 150000
#include "common/pg_prng.h"
#endif
#ifdef IVFFLAT_BENCH
#include "portability/instr_time.h"
#endif
#define IVFFLAT_MAX_DIM 2000
/* Support functions */
#define IVFFLAT_DISTANCE_PROC 1
#define IVFFLAT_NORM_PROC 2
@@ -27,25 +42,52 @@
#define IVFFLAT_DEFAULT_LISTS 100
#define IVFFLAT_MAX_LISTS 32768
/* Build phases */
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
#define PROGRESS_IVFFLAT_PHASE_KMEANS 2
#define PROGRESS_IVFFLAT_PHASE_SORT 3
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
#if PG_VERSION_NUM < 100000
#define ItemPointerGetBlockNumberNoCheck ItemPointerGetBlockNumber
#define ItemPointerGetOffsetNumberNoCheck ItemPointerGetOffsetNumber
#ifdef IVFFLAT_BENCH
#define IvfflatBench(name, code) \
do { \
instr_time start; \
instr_time duration; \
INSTR_TIME_SET_CURRENT(start); \
(code); \
INSTR_TIME_SET_CURRENT(duration); \
INSTR_TIME_SUBTRACT(duration, start); \
elog(INFO, "%s: %.3f ms", name, INSTR_TIME_GET_MILLISEC(duration)); \
} while (0)
#else
#define IvfflatBench(name, code) (code)
#endif
#if PG_VERSION_NUM >= 150000
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
#define RandomInt() pg_prng_uint32(&pg_global_prng_state)
#else
#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
#define RandomInt() random()
#endif
/* Variables */
extern int ivfflat_probes;
/* Exported functions */
PGDLLEXPORT void _PG_init(void);
typedef struct VectorArrayData
{
int length;
int maxlen;
int dim;
Vector items[FLEXIBLE_ARRAY_MEMBER];
Vector *items;
} VectorArrayData;
typedef VectorArrayData * VectorArray;
@@ -90,6 +132,12 @@ typedef struct IvfflatBuildState
ListInfo *listInfo;
Vector *normvec;
#ifdef IVFFLAT_KMEANS_DEBUG
double inertia;
double *listSums;
int *listCounts;
#endif
/* Sampling */
BlockSamplerData bs;
ReservoirStateData rstate;
@@ -99,6 +147,9 @@ typedef struct IvfflatBuildState
Tuplesortstate *sortstate;
TupleDesc tupdesc;
TupleTableSlot *slot;
/* Memory */
MemoryContext tmpCtx;
} IvfflatBuildState;
typedef struct IvfflatMetaPageData
@@ -131,6 +182,7 @@ typedef IvfflatListData * IvfflatList;
typedef struct IvfflatScanList
{
pairingheap_node ph_node;
BlockNumber startPage;
double distance;
} IvfflatScanList;
@@ -152,37 +204,41 @@ typedef struct IvfflatScanOpaqueData
FmgrInfo *normprocinfo;
Oid collation;
/* Lists */
pairingheap *listQueue;
IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER]; /* must come last */
} IvfflatScanOpaqueData;
typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
#define VECTOR_ARRAY_SIZE(_length, _dim) (offsetof(VectorArrayData, items) + _length * VECTOR_SIZE(_dim))
#define VECTOR_ARRAY_OFFSET(_arr, _offset) ((char*) _arr + offsetof(VectorArrayData, items) + (_offset) * VECTOR_SIZE(_arr->dim))
#define VECTOR_ARRAY_SIZE(_length, _dim) (sizeof(VectorArrayData) + (_length) * VECTOR_SIZE(_dim))
#define VECTOR_ARRAY_OFFSET(_arr, _offset) ((char*) (_arr)->items + (_offset) * VECTOR_SIZE((_arr)->dim))
#define VectorArrayGet(_arr, _offset) ((Vector *) VECTOR_ARRAY_OFFSET(_arr, _offset))
#define VectorArraySet(_arr, _offset, _val) (memcpy(VECTOR_ARRAY_OFFSET(_arr, _offset), _val, VECTOR_SIZE(_arr->dim)))
#define VectorArraySet(_arr, _offset, _val) memcpy(VECTOR_ARRAY_OFFSET(_arr, _offset), _val, VECTOR_SIZE((_arr)->dim))
/* Methods */
void _PG_init(void);
VectorArray VectorArrayInit(int maxlen, int dimensions);
void VectorArrayFree(VectorArray arr);
void PrintVectorArray(char *msg, VectorArray arr);
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
FmgrInfo *IvfflatOptionalProcInfo(Relation rel, uint16 procnum);
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
int IvfflatGetLists(Relation index);
void IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo, BlockNumber insertPage, BlockNumber startPage, ForkNumber forkNum);
void IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
Buffer IvfflatNewBuffer(Relation index, ForkNumber forkNum);
void IvfflatInitPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state);
void IvfflatInitPage(Buffer buf, Page page);
void IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state);
/* Index access methods */
IndexBuildResult *ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo);
void ivfflatbuildempty(Relation index);
bool ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heap, IndexUniqueCheck checkUnique
#if PG_VERSION_NUM >= 100000
,IndexInfo *indexInfo
#if PG_VERSION_NUM >= 140000
,bool indexUnchanged
#endif
,IndexInfo *indexInfo
);
IndexBulkDeleteResult *ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
IndexBulkDeleteResult *ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats);

View File

@@ -4,6 +4,7 @@
#include "ivfflat.h"
#include "storage/bufmgr.h"
#include "utils/memutils.h"
/*
* Find the list that minimizes the distance function
@@ -53,44 +54,59 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
}
}
/*
* Prepare to insert an index tuple
*/
static void
LoadInsertPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, BlockNumber insertPage)
{
*buf = ReadBuffer(index, insertPage);
LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
*state = GenericXLogStart(index);
*page = GenericXLogRegisterBuffer(*state, *buf, 0);
}
/*
* Insert a tuple into the index
*/
static void
InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
{
IndexTuple itup;
Datum value;
FmgrInfo *normprocinfo;
Buffer buf;
Page page;
GenericXLogState *state;
Size itemsz;
BlockNumber insertPage = InvalidBlockNumber;
ListInfo listInfo;
bool newPage = false;
BlockNumber originalInsertPage;
/* Detoast once for all calls */
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/* Normalize if needed */
normprocinfo = IvfflatOptionalProcInfo(rel, IVFFLAT_NORM_PROC);
if (normprocinfo != NULL)
{
if (!IvfflatNormValue(normprocinfo, rel->rd_indcollation[0], &value, NULL))
return;
}
/* Find the insert page - sets the page and list info */
FindInsertPage(rel, values, &insertPage, &listInfo);
Assert(BlockNumberIsValid(insertPage));
originalInsertPage = insertPage;
/* Form tuple */
itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
itup->t_tid = *heap_tid;
/* Get tuple size */
itemsz = MAXALIGN(IndexTupleSize(itup));
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
LoadInsertPage(rel, &buf, &page, &state, insertPage);
/* Find a page to insert the item */
while (PageGetFreeSpace(page) < itemsz)
for (;;)
{
buf = ReadBuffer(rel, insertPage);
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
state = GenericXLogStart(rel);
page = GenericXLogRegisterBuffer(state, buf, 0);
if (PageGetFreeSpace(page) >= itemsz)
break;
insertPage = IvfflatPageGetOpaque(page)->nextblkno;
if (BlockNumberIsValid(insertPage))
@@ -98,16 +114,50 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
/* Move to next page */
GenericXLogAbort(state);
UnlockReleaseBuffer(buf);
LoadInsertPage(rel, &buf, &page, &state, insertPage);
}
else
{
/* Add a new page */
IvfflatAppendPage(rel, &buf, &page, &state, MAIN_FORKNUM);
Buffer metabuf;
Buffer newbuf;
Page newpage;
insertPage = BufferGetBlockNumber(buf);
newPage = true;
/*
* From ReadBufferExtended: Caller is responsible for ensuring
* that only one backend tries to extend a relation at the same
* time!
*/
metabuf = ReadBuffer(rel, IVFFLAT_METAPAGE_BLKNO);
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
/* Add a new page */
newbuf = IvfflatNewBuffer(rel, MAIN_FORKNUM);
newpage = GenericXLogRegisterBuffer(state, newbuf, GENERIC_XLOG_FULL_IMAGE);
/* Init new page */
IvfflatInitPage(newbuf, newpage);
/* Update insert page */
insertPage = BufferGetBlockNumber(newbuf);
/* Update previous buffer */
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
/* Commit */
MarkBufferDirty(newbuf);
MarkBufferDirty(buf);
GenericXLogFinish(state);
/* Unlock extend relation lock as early as possible */
UnlockReleaseBuffer(metabuf);
/* Unlock previous buffer */
UnlockReleaseBuffer(buf);
/* Prepare new buffer */
state = GenericXLogStart(rel);
buf = newbuf;
page = GenericXLogRegisterBuffer(state, buf, 0);
break;
}
}
@@ -118,8 +168,8 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
IvfflatCommitBuffer(buf, state);
/* Update the insert page */
if (newPage)
IvfflatUpdateList(rel, state, listInfo, insertPage, InvalidBlockNumber, MAIN_FORKNUM);
if (insertPage != originalInsertPage)
IvfflatUpdateList(rel, state, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
}
/*
@@ -128,36 +178,34 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
bool
ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid,
Relation heap, IndexUniqueCheck checkUnique
#if PG_VERSION_NUM >= 100000
,IndexInfo *indexInfo
#if PG_VERSION_NUM >= 140000
,bool indexUnchanged
#endif
,IndexInfo *indexInfo
)
{
IndexTuple itup;
Datum value;
FmgrInfo *normprocinfo;
MemoryContext oldCtx;
MemoryContext insertCtx;
/* Skip nulls */
if (isnull[0])
return false;
value = values[0];
/*
* Use memory context since detoast, IvfflatNormValue, and
* index_form_tuple can allocate
*/
insertCtx = AllocSetContextCreate(CurrentMemoryContext,
"Ivfflat insert temporary context",
ALLOCSET_DEFAULT_SIZES);
oldCtx = MemoryContextSwitchTo(insertCtx);
/* Normalize if needed */
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
if (normprocinfo != NULL)
{
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, NULL))
return false;
}
/* Insert tuple */
InsertTuple(index, values, isnull, heap_tid, heap);
itup = index_form_tuple(RelationGetDescr(index), &value, isnull);
itup->t_tid = *heap_tid;
InsertTuple(index, itup, heap, &value);
pfree(itup);
/* Clean up if we allocated a new value */
if (value != values[0])
pfree(DatumGetPointer(value));
/* Delete memory context */
MemoryContextSwitchTo(oldCtx);
MemoryContextDelete(insertCtx);
return false;
}

View File

@@ -11,17 +11,17 @@
* https://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf
*/
static void
InitCenters(Relation index, VectorArray samples, VectorArray centers, double *lowerBound)
InitCenters(Relation index, VectorArray samples, VectorArray centers, float *lowerBound)
{
FmgrInfo *procinfo;
Oid collation;
int i;
int j;
int64 j;
double distance;
double sum;
double choice;
Vector *vec;
double *weight = palloc(samples->length * sizeof(double));
float *weight = palloc(samples->length * sizeof(float));
int numCenters = centers->maxlen;
int numSamples = samples->length;
@@ -29,7 +29,7 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, double *lo
collation = index->rd_indcollation[0];
/* Choose an initial center uniformly at random */
VectorArraySet(centers, 0, VectorArrayGet(samples, random() % samples->length));
VectorArraySet(centers, 0, VectorArrayGet(samples, RandomInt() % samples->length));
centers->length++;
for (j = 0; j < numSamples; j++)
@@ -66,7 +66,7 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, double *lo
break;
/* Choose new center using weighted probability distribution. */
choice = sum * (((double) random()) / MAX_RANDOM_VALUE);
choice = sum * RandomDouble();
for (j = 0; j < numSamples - 1; j++)
{
choice -= weight[j];
@@ -121,15 +121,18 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
/* Copy existing vectors while avoiding duplicates */
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
for (i = 0; i < samples->length; i++)
if (samples->length > 0)
{
vec = VectorArrayGet(samples, i);
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
for (i = 0; i < samples->length; i++)
{
VectorArraySet(centers, centers->length, vec);
centers->length++;
vec = VectorArrayGet(samples, i);
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
{
VectorArraySet(centers, centers->length, vec);
centers->length++;
}
}
}
@@ -142,7 +145,7 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
vec->dim = dimensions;
for (j = 0; j < dimensions; j++)
vec->x[j] = ((double) random()) / MAX_RANDOM_VALUE;
vec->x[j] = RandomDouble();
/* Normalize if needed (only needed for random centers) */
if (normprocinfo != NULL)
@@ -169,19 +172,19 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
Vector *vec;
Vector *newCenter;
int iteration;
int j;
int k;
int64 j;
int64 k;
int dimensions = centers->dim;
int numCenters = centers->maxlen;
int numSamples = samples->length;
VectorArray newCenters;
int *centerCounts;
int *closestCenters;
double *lowerBound;
double *upperBound;
double *s;
double *halfcdist;
double *newcdist;
float *lowerBound;
float *upperBound;
float *s;
float *halfcdist;
float *newcdist;
int changes;
double minDistance;
int closestCenter;
@@ -191,19 +194,47 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
double dxcx;
double dxc;
/* Calculate allocation sizes */
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
Size centersSize = VECTOR_ARRAY_SIZE(centers->maxlen, centers->dim);
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, dimensions);
Size centerCountsSize = sizeof(int) * numCenters;
Size closestCentersSize = sizeof(int) * numSamples;
Size lowerBoundSize = sizeof(float) * numSamples * numCenters;
Size upperBoundSize = sizeof(float) * numSamples;
Size sSize = sizeof(float) * numCenters;
Size halfcdistSize = sizeof(float) * numCenters * numCenters;
Size newcdistSize = sizeof(float) * numCenters;
/* Calculate total size */
Size totalSize = samplesSize + centersSize + newCentersSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
/* Check memory requirements */
/* Add one to error message to ceil */
if (totalSize / 1024 > maintenance_work_mem)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("memory required is %zu MB, maintenance_work_mem is %d MB",
totalSize / (1024 * 1024) + 1, maintenance_work_mem / 1024)));
/* Ensure indexing does not overflow */
if (numCenters * numCenters > INT_MAX)
elog(ERROR, "Indexing overflow detected. Please report a bug.");
/* Set support functions */
procinfo = index_getprocinfo(index, 1, IVFFLAT_KMEANS_DISTANCE_PROC);
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
collation = index->rd_indcollation[0];
/* Allocate space */
centerCounts = palloc(sizeof(int) * numCenters);
closestCenters = palloc(sizeof(int) * numSamples);
lowerBound = palloc(sizeof(double) * numSamples * numCenters);
upperBound = palloc(sizeof(double) * numSamples);
s = palloc(sizeof(double) * numCenters);
halfcdist = palloc(sizeof(double) * numCenters * numCenters);
newcdist = palloc(sizeof(double) * numCenters);
/* Use float instead of double to save memory */
centerCounts = palloc(centerCountsSize);
closestCenters = palloc(closestCentersSize);
lowerBound = palloc_extended(lowerBoundSize, MCXT_ALLOC_HUGE);
upperBound = palloc(upperBoundSize);
s = palloc(sSize);
halfcdist = palloc_extended(halfcdistSize, MCXT_ALLOC_HUGE);
newcdist = palloc(newcdistSize);
newCenters = VectorArrayInit(numCenters, dimensions);
for (j = 0; j < numCenters; j++)
@@ -222,8 +253,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
minDistance = DBL_MAX;
closestCenter = -1;
vec = VectorArrayGet(samples, j);
/* Find closest center */
for (k = 0; k < numCenters; k++)
{
@@ -376,7 +405,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
{
/* TODO Handle empty centers properly */
for (k = 0; k < dimensions; k++)
vec->x[k] = ((double) random()) / MAX_RANDOM_VALUE;
vec->x[k] = RandomDouble();
}
/* Normalize if needed */
@@ -414,7 +443,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
break;
}
pfree(newCenters);
VectorArrayFree(newCenters);
pfree(centerCounts);
pfree(closestCenters);
pfree(lowerBound);

View File

@@ -1,30 +1,26 @@
#include "postgres.h"
#include <float.h>
#include "access/relscan.h"
#include "ivfflat.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/bufmgr.h"
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_d.h"
#include "catalog/pg_type_d.h"
#else
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#endif
/*
* Compare list distances
*/
static int
CompareLists(const void *a, const void *b)
CompareLists(const pairingheap_node *a, const pairingheap_node *b, void *arg)
{
double diff = (((IvfflatScanList *) a)->distance - ((IvfflatScanList *) b)->distance);
if (diff > 0)
if (((const IvfflatScanList *) a)->distance > ((const IvfflatScanList *) b)->distance)
return 1;
if (diff < 0)
if (((const IvfflatScanList *) a)->distance < ((const IvfflatScanList *) b)->distance)
return -1;
return 0;
@@ -45,6 +41,8 @@ GetScanLists(IndexScanDesc scan, Datum value)
int listCount = 0;
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
double distance;
IvfflatScanList *scanlist;
double maxDistance = DBL_MAX;
/* Search all list pages */
while (BlockNumberIsValid(nextblkno))
@@ -62,21 +60,39 @@ GetScanLists(IndexScanDesc scan, Datum value)
/* Use procinfo from the index instead of scan key for performance */
distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
so->lists[listCount].startPage = list->startPage;
so->lists[listCount].distance = distance;
listCount++;
if (listCount < so->probes)
{
scanlist = &so->lists[listCount];
scanlist->startPage = list->startPage;
scanlist->distance = distance;
listCount++;
/* Add to heap */
pairingheap_add(so->listQueue, &scanlist->ph_node);
/* Calculate max distance */
if (listCount == so->probes)
maxDistance = ((IvfflatScanList *) pairingheap_first(so->listQueue))->distance;
}
else if (distance < maxDistance)
{
/* Remove */
scanlist = (IvfflatScanList *) pairingheap_remove_first(so->listQueue);
/* Reuse */
scanlist->startPage = list->startPage;
scanlist->distance = distance;
pairingheap_add(so->listQueue, &scanlist->ph_node);
/* Update max distance */
maxDistance = ((IvfflatScanList *) pairingheap_first(so->listQueue))->distance;
}
}
nextblkno = IvfflatPageGetOpaque(cpage)->nextblkno;
UnlockReleaseBuffer(cbuf);
}
/* Sort by distance */
qsort(so->lists, listCount, sizeof(IvfflatScanList), CompareLists);
if (so->probes > listCount)
so->probes = listCount;
}
/*
@@ -94,8 +110,8 @@ GetScanItems(IndexScanDesc scan, Datum value)
OffsetNumber maxoffno;
Datum datum;
bool isnull;
int i;
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
double tuples = 0;
#if PG_VERSION_NUM >= 120000
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual);
@@ -108,12 +124,12 @@ GetScanItems(IndexScanDesc scan, Datum value)
*
* See postgres/src/backend/storage/buffer/README for description
*/
BufferAccessStrategy bas = GetAccessStrategy(BAS_BULKREAD);
BufferAccessStrategy bas = GetAccessStrategy(BAS_NORMAL);
/* Search closest probes lists */
for (i = 0; i < so->probes; i++)
while (!pairingheap_is_empty(so->listQueue))
{
searchPage = so->lists[i].startPage;
searchPage = ((IvfflatScanList *) pairingheap_remove_first(so->listQueue))->startPage;
/* Search all entry pages for list */
while (BlockNumberIsValid(searchPage))
@@ -137,15 +153,15 @@ GetScanItems(IndexScanDesc scan, Datum value)
ExecClearTuple(slot);
slot->tts_values[0] = FunctionCall2Coll(so->procinfo, so->collation, datum, value);
slot->tts_isnull[0] = false;
slot->tts_values[1] = Int32GetDatum((int) ItemPointerGetBlockNumberNoCheck(&itup->t_tid));
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
slot->tts_isnull[1] = false;
slot->tts_values[2] = Int32GetDatum((int) ItemPointerGetOffsetNumberNoCheck(&itup->t_tid));
slot->tts_values[2] = Int32GetDatum((int) searchPage);
slot->tts_isnull[2] = false;
slot->tts_values[3] = Int32GetDatum((int) searchPage);
slot->tts_isnull[3] = false;
ExecStoreVirtualTuple(slot);
tuplesort_puttupleslot(so->sortstate, slot);
tuples++;
}
searchPage = IvfflatPageGetOpaque(page)->nextblkno;
@@ -153,6 +169,15 @@ GetScanItems(IndexScanDesc scan, Datum value)
UnlockReleaseBuffer(buf);
}
}
/* TODO Scan more lists */
if (tuples < 100)
ereport(DEBUG1,
(errmsg("index scan found few tuples"),
errdetail("index may have been created without data or lists is too high"),
errhint("recreate the index and possibly decrease lists")));
tuplesort_performsort(so->sortstate);
}
/*
@@ -168,13 +193,18 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
Oid sortOperators[] = {Float8LessOperator};
Oid sortCollations[] = {InvalidOid};
bool nullsFirstFlags[] = {false};
int probes = ivfflat_probes;
scan = RelationGetIndexScan(index, nkeys, norderbys);
lists = IvfflatGetLists(scan->indexRelation);
so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + lists * sizeof(IvfflatScanList));
if (probes > lists)
probes = lists;
so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + probes * sizeof(IvfflatScanList));
so->buf = InvalidBuffer;
so->first = true;
so->probes = probes;
/* Set support functions */
so->procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
@@ -183,21 +213,16 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
/* Create tuple description for sorting */
#if PG_VERSION_NUM >= 120000
so->tupdesc = CreateTemplateTupleDesc(4);
so->tupdesc = CreateTemplateTupleDesc(3);
#else
so->tupdesc = CreateTemplateTupleDesc(4, false);
so->tupdesc = CreateTemplateTupleDesc(3, false);
#endif
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "blkno", INT4OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "offset", INT4OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 4, "indexblkno", INT4OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
/* Prep sort */
#if PG_VERSION_NUM >= 110000
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
#else
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, false);
#endif
#if PG_VERSION_NUM >= 120000
so->slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple);
@@ -205,6 +230,8 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
so->slot = MakeSingleTupleTableSlot(so->tupdesc);
#endif
so->listQueue = pairingheap_allocate(CompareLists, scan);
scan->opaque = so;
return scan;
@@ -224,7 +251,7 @@ ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int
#endif
so->first = true;
so->probes = ivfflat_probes;
pairingheap_reset(so->listQueue);
if (keys && scan->numberOfKeys > 0)
memmove(scan->keyData, keys, scan->numberOfKeys * sizeof(ScanKeyData));
@@ -251,6 +278,9 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
{
Datum value;
/* Count index scan for stats */
pgstat_count_index_scan(scan->indexRelation);
/* Safety check */
if (scan->orderByData == NULL)
elog(ERROR, "cannot scan ivfflat index without order");
@@ -261,6 +291,10 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
value = scan->orderByData->sk_argument;
/* Value should not be compressed or toasted */
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
if (so->normprocinfo != NULL)
{
/* No items will match if normalization fails */
@@ -268,9 +302,8 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
return false;
}
GetScanLists(scan, value);
GetScanItems(scan, value);
tuplesort_performsort(so->sortstate);
IvfflatBench("GetScanLists", GetScanLists(scan, value));
IvfflatBench("GetScanItems", GetScanItems(scan, value));
so->first = false;
/* Clean up if we allocated a new value */
@@ -278,20 +311,15 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
pfree(DatumGetPointer(value));
}
#if PG_VERSION_NUM >= 100000
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL))
#else
if (tuplesort_gettupleslot(so->sortstate, true, so->slot, NULL))
#endif
{
BlockNumber blkno = DatumGetInt32(slot_getattr(so->slot, 2, &so->isnull));
OffsetNumber offset = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 4, &so->isnull));
ItemPointer tid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
#if PG_VERSION_NUM >= 120000
ItemPointerSet(&scan->xs_heaptid, blkno, offset);
scan->xs_heaptid = *tid;
#else
ItemPointerSet(&scan->xs_ctup.t_self, blkno, offset);
scan->xs_ctup.t_self = *tid;
#endif
if (BufferIsValid(so->buf))
@@ -324,6 +352,7 @@ ivfflatendscan(IndexScanDesc scan)
if (BufferIsValid(so->buf))
ReleaseBuffer(so->buf);
pairingheap_free(so->listQueue);
tuplesort_end(so->sortstate);
pfree(so);

View File

@@ -10,14 +10,25 @@
VectorArray
VectorArrayInit(int maxlen, int dimensions)
{
VectorArray res = palloc0(VECTOR_ARRAY_SIZE(maxlen, dimensions));
VectorArray res = palloc(sizeof(VectorArrayData));
res->length = 0;
res->maxlen = maxlen;
res->dim = dimensions;
res->items = palloc_extended(maxlen * VECTOR_SIZE(dimensions), MCXT_ALLOC_ZERO | MCXT_ALLOC_HUGE);
return res;
}
/*
* Free a vector array
*/
void
VectorArrayFree(VectorArray arr)
{
pfree(arr->items);
pfree(arr);
}
/*
* Print vector array - useful for debugging
*/
@@ -75,7 +86,7 @@ IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * resul
if (norm > 0)
{
v = (Vector *) DatumGetPointer(*value);
v = DatumGetVector(*value);
if (result == NULL)
result = InitVector(v->dim);
@@ -107,13 +118,22 @@ IvfflatNewBuffer(Relation index, ForkNumber forkNum)
* Init page
*/
void
IvfflatInitPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state)
IvfflatInitPage(Buffer buf, Page page)
{
PageInit(page, BufferGetPageSize(buf), sizeof(IvfflatPageOpaqueData));
IvfflatPageGetOpaque(page)->nextblkno = InvalidBlockNumber;
IvfflatPageGetOpaque(page)->page_id = IVFFLAT_PAGE_ID;
}
/*
* Init and register page
*/
void
IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state)
{
*state = GenericXLogStart(index);
*page = GenericXLogRegisterBuffer(*state, *buf, GENERIC_XLOG_FULL_IMAGE);
PageInit(*page, BufferGetPageSize(*buf), sizeof(IvfflatPageOpaqueData));
IvfflatPageGetOpaque(*page)->nextblkno = InvalidBlockNumber;
IvfflatPageGetOpaque(*page)->page_id = IVFFLAT_PAGE_ID;
IvfflatInitPage(*buf, *page);
}
/*
@@ -135,17 +155,27 @@ IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
void
IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum)
{
Buffer prevbuf = *buf;
/* Get new buffer */
*buf = IvfflatNewBuffer(index, forkNum);
Buffer newbuf = IvfflatNewBuffer(index, forkNum);
Page newpage = GenericXLogRegisterBuffer(*state, newbuf, GENERIC_XLOG_FULL_IMAGE);
/* Update and commit previous buffer */
IvfflatPageGetOpaque(*page)->nextblkno = BufferGetBlockNumber(*buf);
IvfflatCommitBuffer(prevbuf, *state);
/* Update the previous buffer */
IvfflatPageGetOpaque(*page)->nextblkno = BufferGetBlockNumber(newbuf);
/* Init new page */
IvfflatInitPage(index, buf, page, state);
IvfflatInitPage(newbuf, newpage);
/* Commit */
MarkBufferDirty(*buf);
MarkBufferDirty(newbuf);
GenericXLogFinish(*state);
/* Unlock */
UnlockReleaseBuffer(*buf);
*state = GenericXLogStart(index);
*page = GenericXLogRegisterBuffer(*state, newbuf, GENERIC_XLOG_FULL_IMAGE);
*buf = newbuf;
}
/*
@@ -153,11 +183,13 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
*/
void
IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo,
BlockNumber insertPage, BlockNumber startPage, ForkNumber forkNum)
BlockNumber insertPage, BlockNumber originalInsertPage,
BlockNumber startPage, ForkNumber forkNum)
{
Buffer buf;
Page page;
IvfflatList list;
bool changed = false;
buf = ReadBufferExtended(index, forkNum, listInfo.blkno, RBM_NORMAL, NULL);
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
@@ -165,12 +197,29 @@ IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo,
page = GenericXLogRegisterBuffer(state, buf, 0);
list = (IvfflatList) PageGetItem(page, PageGetItemId(page, listInfo.offno));
if (BlockNumberIsValid(insertPage))
list->insertPage = insertPage;
if (BlockNumberIsValid(insertPage) && insertPage != list->insertPage)
{
/* Skip update if insert page is lower than original insert page */
/* This is needed to prevent insert from overwriting vacuum */
if (!BlockNumberIsValid(originalInsertPage) || insertPage >= originalInsertPage)
{
list->insertPage = insertPage;
changed = true;
}
}
if (BlockNumberIsValid(startPage))
if (BlockNumberIsValid(startPage) && startPage != list->startPage)
{
list->startPage = startPage;
changed = true;
}
/* Could only commit if changed, but extra complexity isn't needed */
IvfflatCommitBuffer(buf, state);
/* Only commit if changed */
if (changed)
IvfflatCommitBuffer(buf, state);
else
{
GenericXLogAbort(state);
UnlockReleaseBuffer(buf);
}
}

View File

@@ -21,7 +21,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
ItemPointer htup;
OffsetNumber deletable[MaxOffsetNumber];
int ndeletable;
OffsetNumber startPages[MaxOffsetNumber];
BlockNumber startPages[MaxOffsetNumber];
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
BlockNumber searchPage;
BlockNumber insertPage;
@@ -98,6 +98,11 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
stats->num_index_tuples++;
}
/* Set to first free page */
/* Must be set before searchPage is updated */
if (!BlockNumberIsValid(insertPage) && ndeletable > 0)
insertPage = searchPage;
searchPage = IvfflatPageGetOpaque(page)->nextblkno;
if (ndeletable > 0)
@@ -106,10 +111,6 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
PageIndexMultiDelete(page, deletable, ndeletable);
MarkBufferDirty(buf);
GenericXLogFinish(state);
/* Set to first free page */
if (!BlockNumberIsValid(insertPage))
insertPage = searchPage;
}
else
GenericXLogAbort(state);
@@ -123,10 +124,10 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
* We don't add or delete items from lists pages, so offset won't
* change.
*/
if (!BlockNumberIsValid(insertPage))
if (BlockNumberIsValid(insertPage))
{
listInfo.offno = coffno;
IvfflatUpdateList(index, state, listInfo, insertPage, InvalidBlockNumber, MAIN_FORKNUM);
IvfflatUpdateList(index, state, listInfo, insertPage, InvalidBlockNumber, InvalidBlockNumber, MAIN_FORKNUM);
}
}
}
@@ -142,6 +143,11 @@ ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
{
Relation rel = info->index;
if (info->analyze_only)
return stats;
/* stats is NULL if ambulkdelete not called */
/* OK to return NULL if index not changed */
if (stats == NULL)
return NULL;

View File

@@ -13,9 +13,20 @@
#include "utils/numeric.h"
#if PG_VERSION_NUM >= 120000
#include "common/shortest_dec.h"
#include "utils/float.h"
#else
#include <float.h>
#endif
#if PG_VERSION_NUM < 130000
#define TYPALIGN_DOUBLE 'd'
#define TYPALIGN_INT 'i'
#endif
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
PG_MODULE_MAGIC;
/*
@@ -75,6 +86,30 @@ CheckElement(float value)
errmsg("infinite value not allowed in vector")));
}
/*
* Check state array
*/
static float8 *
CheckStateArray(ArrayType *statearray, const char *caller)
{
if (ARR_NDIM(statearray) != 1 ||
ARR_DIMS(statearray)[0] < 1 ||
ARR_HASNULL(statearray) ||
ARR_ELEMTYPE(statearray) != FLOAT8OID)
elog(ERROR, "%s: expected state array", caller);
return (float8 *) ARR_DATA_PTR(statearray);
}
#if PG_VERSION_NUM < 120000
static pg_noinline void
float_overflow_error(void)
{
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("value out of range: overflow")));
}
#endif
/*
* Print vector - useful for debugging
*/
@@ -102,14 +137,14 @@ PrintVector(char *msg, Vector * vector)
/*
* Convert textual representation to internal representation
*/
PG_FUNCTION_INFO_V1(vector_in);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_in);
Datum
vector_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
int32 typmod = PG_GETARG_INT32(2);
int i;
double x[VECTOR_MAX_DIM];
float x[VECTOR_MAX_DIM];
int dim = 0;
char *pt;
char *stringEnd;
@@ -132,7 +167,8 @@ vector_in(PG_FUNCTION_ARGS)
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("vector cannot have more than %d dimensions", VECTOR_MAX_DIM)));
x[dim] = strtod(pt, &stringEnd);
/* Use strtof like float4in to avoid a double-rounding problem */
x[dim] = strtof(pt, &stringEnd);
CheckElement(x[dim]);
dim++;
@@ -178,35 +214,68 @@ vector_in(PG_FUNCTION_ARGS)
/*
* Convert internal representation to textual representation
*/
PG_FUNCTION_INFO_V1(vector_out);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_out);
Datum
vector_out(PG_FUNCTION_ARGS)
{
Vector *vector = PG_GETARG_VECTOR_P(0);
StringInfoData buf;
int dim = vector->dim;
char *buf;
char *ptr;
int i;
int n;
initStringInfo(&buf);
#if PG_VERSION_NUM < 120000
int ndig = FLT_DIG + extra_float_digits;
appendStringInfoChar(&buf, '[');
if (ndig < 1)
ndig = 1;
#define FLOAT_SHORTEST_DECIMAL_LEN (ndig + 10)
#endif
/*
* Need:
*
* dim * (FLOAT_SHORTEST_DECIMAL_LEN - 1) bytes for
* float_to_shortest_decimal_bufn
*
* dim - 1 bytes for separator
*
* 3 bytes for [, ], and \0
*/
buf = (char *) palloc(FLOAT_SHORTEST_DECIMAL_LEN * dim + 2);
ptr = buf;
*ptr = '[';
ptr++;
for (i = 0; i < dim; i++)
{
if (i > 0)
appendStringInfoString(&buf, ",");
{
*ptr = ',';
ptr++;
}
appendStringInfoString(&buf, float8out_internal(vector->x[i]));
#if PG_VERSION_NUM >= 120000
n = float_to_shortest_decimal_bufn(vector->x[i], ptr);
#else
n = sprintf(ptr, "%.*g", ndig, vector->x[i]);
#endif
ptr += n;
}
appendStringInfoChar(&buf, ']');
*ptr = ']';
ptr++;
*ptr = '\0';
PG_FREE_IF_COPY(vector, 0);
PG_RETURN_CSTRING(buf.data);
PG_RETURN_CSTRING(buf);
}
/*
* Convert type modifier
*/
PG_FUNCTION_INFO_V1(vector_typmod_in);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_typmod_in);
Datum
vector_typmod_in(PG_FUNCTION_ARGS)
{
@@ -237,7 +306,7 @@ vector_typmod_in(PG_FUNCTION_ARGS)
/*
* Convert external binary representation to internal representation
*/
PG_FUNCTION_INFO_V1(vector_recv);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_recv);
Datum
vector_recv(PG_FUNCTION_ARGS)
{
@@ -269,7 +338,7 @@ vector_recv(PG_FUNCTION_ARGS)
/*
* Convert internal representation to the external binary representation
*/
PG_FUNCTION_INFO_V1(vector_send);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_send);
Datum
vector_send(PG_FUNCTION_ARGS)
{
@@ -289,7 +358,7 @@ vector_send(PG_FUNCTION_ARGS)
/*
* Convert vector to vector
*/
PG_FUNCTION_INFO_V1(vector);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector);
Datum
vector(PG_FUNCTION_ARGS)
{
@@ -304,7 +373,7 @@ vector(PG_FUNCTION_ARGS)
/*
* Convert array to vector
*/
PG_FUNCTION_INFO_V1(array_to_vector);
PGDLLEXPORT PG_FUNCTION_INFO_V1(array_to_vector);
Datum
array_to_vector(PG_FUNCTION_ARGS)
{
@@ -347,7 +416,7 @@ array_to_vector(PG_FUNCTION_ARGS)
else if (ARR_ELEMTYPE(array) == FLOAT4OID)
result->x[i] = DatumGetFloat4(elemsp[i]);
else if (ARR_ELEMTYPE(array) == NUMERICOID)
result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(elemsp[i])));
result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i]));
else
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
@@ -359,23 +428,49 @@ array_to_vector(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
/*
* Convert vector to float4[]
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_to_float4);
Datum
vector_to_float4(PG_FUNCTION_ARGS)
{
Vector *vec = PG_GETARG_VECTOR_P(0);
Datum *d;
ArrayType *result;
int i;
d = (Datum *) palloc(sizeof(Datum) * vec->dim);
for (i = 0; i < vec->dim; i++)
d[i] = Float4GetDatum(vec->x[i]);
/* Use TYPALIGN_INT for float4 */
result = construct_array(d, vec->dim, FLOAT4OID, sizeof(float4), true, TYPALIGN_INT);
PG_RETURN_POINTER(result);
}
/*
* Get the L2 distance between vectors
*/
PG_FUNCTION_INFO_V1(l2_distance);
PGDLLEXPORT PG_FUNCTION_INFO_V1(l2_distance);
Datum
l2_distance(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
double distance = 0.0;
double diff;
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
{
diff = a->x[i] - b->x[i];
diff = ax[i] - bx[i];
distance += diff * diff;
}
@@ -386,20 +481,23 @@ l2_distance(PG_FUNCTION_ARGS)
* Get the L2 squared distance between vectors
* This saves a sqrt calculation
*/
PG_FUNCTION_INFO_V1(vector_l2_squared_distance);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_l2_squared_distance);
Datum
vector_l2_squared_distance(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
double distance = 0.0;
double diff;
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
{
diff = a->x[i] - b->x[i];
diff = ax[i] - bx[i];
distance += diff * diff;
}
@@ -409,18 +507,21 @@ vector_l2_squared_distance(PG_FUNCTION_ARGS)
/*
* Get the inner product of two vectors
*/
PG_FUNCTION_INFO_V1(inner_product);
PGDLLEXPORT PG_FUNCTION_INFO_V1(inner_product);
Datum
inner_product(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
double distance = 0.0;
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
distance += a->x[i] * b->x[i];
distance += ax[i] * bx[i];
PG_RETURN_FLOAT8(distance);
}
@@ -428,18 +529,21 @@ inner_product(PG_FUNCTION_ARGS)
/*
* Get the negative inner product of two vectors
*/
PG_FUNCTION_INFO_V1(vector_negative_inner_product);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_negative_inner_product);
Datum
vector_negative_inner_product(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
double distance = 0.0;
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
distance += a->x[i] * b->x[i];
distance += ax[i] * bx[i];
PG_RETURN_FLOAT8(distance * -1);
}
@@ -447,26 +551,30 @@ vector_negative_inner_product(PG_FUNCTION_ARGS)
/*
* Get the cosine distance between two vectors
*/
PG_FUNCTION_INFO_V1(cosine_distance);
PGDLLEXPORT PG_FUNCTION_INFO_V1(cosine_distance);
Datum
cosine_distance(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
double distance = 0.0;
double norma = 0.0;
double normb = 0.0;
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
{
distance += a->x[i] * b->x[i];
norma += a->x[i] * a->x[i];
normb += b->x[i] * b->x[i];
distance += ax[i] * bx[i];
norma += ax[i] * ax[i];
normb += bx[i] * bx[i];
}
PG_RETURN_FLOAT8(1 - (distance / (sqrt(norma) * sqrt(normb))));
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
PG_RETURN_FLOAT8(1 - (distance / sqrt(norma * normb)));
}
/*
@@ -474,7 +582,7 @@ cosine_distance(PG_FUNCTION_ARGS)
* Currently uses angular distance since needs to satisfy triangle inequality
* Assumes inputs are unit vectors (skips norm)
*/
PG_FUNCTION_INFO_V1(vector_spherical_distance);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_spherical_distance);
Datum
vector_spherical_distance(PG_FUNCTION_ARGS)
{
@@ -484,6 +592,7 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
distance += a->x[i] * b->x[i];
@@ -499,7 +608,7 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
/*
* Get the dimensions of a vector
*/
PG_FUNCTION_INFO_V1(vector_dims);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_dims);
Datum
vector_dims(PG_FUNCTION_ARGS)
{
@@ -511,15 +620,17 @@ vector_dims(PG_FUNCTION_ARGS)
/*
* Get the L2 norm of a vector
*/
PG_FUNCTION_INFO_V1(vector_norm);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_norm);
Datum
vector_norm(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
float *ax = a->x;
double norm = 0.0;
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++)
norm += a->x[i] * a->x[i];
norm += ax[i] * ax[i];
PG_RETURN_FLOAT8(sqrt(norm));
}
@@ -527,20 +638,25 @@ vector_norm(PG_FUNCTION_ARGS)
/*
* Add vectors
*/
PG_FUNCTION_INFO_V1(vector_add);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_add);
Datum
vector_add(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
Vector *result;
int i;
float *rx;
CheckDims(a, b);
result = InitVector(a->dim);
for (i = 0; i < a->dim; i++)
result->x[i] = a->x[i] + b->x[i];
rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] + bx[i];
PG_RETURN_POINTER(result);
}
@@ -548,20 +664,25 @@ vector_add(PG_FUNCTION_ARGS)
/*
* Subtract vectors
*/
PG_FUNCTION_INFO_V1(vector_sub);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_sub);
Datum
vector_sub(PG_FUNCTION_ARGS)
{
Vector *a = PG_GETARG_VECTOR_P(0);
Vector *b = PG_GETARG_VECTOR_P(1);
float *ax = a->x;
float *bx = b->x;
Vector *result;
int i;
float *rx;
CheckDims(a, b);
result = InitVector(a->dim);
for (i = 0; i < a->dim; i++)
result->x[i] = a->x[i] - b->x[i];
rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] - bx[i];
PG_RETURN_POINTER(result);
}
@@ -590,7 +711,7 @@ vector_cmp_internal(Vector * a, Vector * b)
/*
* Less than
*/
PG_FUNCTION_INFO_V1(vector_lt);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_lt);
Datum
vector_lt(PG_FUNCTION_ARGS)
{
@@ -603,7 +724,7 @@ vector_lt(PG_FUNCTION_ARGS)
/*
* Less than or equal
*/
PG_FUNCTION_INFO_V1(vector_le);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_le);
Datum
vector_le(PG_FUNCTION_ARGS)
{
@@ -616,7 +737,7 @@ vector_le(PG_FUNCTION_ARGS)
/*
* Equal
*/
PG_FUNCTION_INFO_V1(vector_eq);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_eq);
Datum
vector_eq(PG_FUNCTION_ARGS)
{
@@ -629,7 +750,7 @@ vector_eq(PG_FUNCTION_ARGS)
/*
* Not equal
*/
PG_FUNCTION_INFO_V1(vector_ne);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_ne);
Datum
vector_ne(PG_FUNCTION_ARGS)
{
@@ -642,7 +763,7 @@ vector_ne(PG_FUNCTION_ARGS)
/*
* Greater than or equal
*/
PG_FUNCTION_INFO_V1(vector_ge);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_ge);
Datum
vector_ge(PG_FUNCTION_ARGS)
{
@@ -655,7 +776,7 @@ vector_ge(PG_FUNCTION_ARGS)
/*
* Greater than
*/
PG_FUNCTION_INFO_V1(vector_gt);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_gt);
Datum
vector_gt(PG_FUNCTION_ARGS)
{
@@ -668,7 +789,7 @@ vector_gt(PG_FUNCTION_ARGS)
/*
* Compare vectors
*/
PG_FUNCTION_INFO_V1(vector_cmp);
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_cmp);
Datum
vector_cmp(PG_FUNCTION_ARGS)
{
@@ -677,3 +798,167 @@ vector_cmp(PG_FUNCTION_ARGS)
PG_RETURN_INT32(vector_cmp_internal(a, b));
}
/*
* Accumulate vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_accum);
Datum
vector_accum(PG_FUNCTION_ARGS)
{
ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
Vector *newval = PG_GETARG_VECTOR_P(1);
float8 *statevalues;
int16 dim;
bool newarr;
float8 n;
Datum *statedatums;
float *x = newval->x;
ArrayType *result;
/* Check array before using */
statevalues = CheckStateArray(statearray, "vector_accum");
dim = STATE_DIMS(statearray);
newarr = dim == 0;
if (newarr)
dim = newval->dim;
else
CheckExpectedDim(dim, newval->dim);
n = statevalues[0] + 1.0;
statedatums = CreateStateDatums(dim);
statedatums[0] = Float8GetDatumFast(n);
if (newarr)
{
for (int i = 0; i < dim; i++)
statedatums[i + 1] = Float8GetDatumFast((double) x[i]);
}
else
{
for (int i = 0; i < dim; i++)
{
double v = statevalues[i + 1] + x[i];
if (isinf(v))
float_overflow_error();
statedatums[i + 1] = Float8GetDatumFast(v);
}
}
/* Use float8 array like float4_accum */
result = construct_array(statedatums, dim + 1,
FLOAT8OID,
sizeof(float8), FLOAT8PASSBYVAL, TYPALIGN_DOUBLE);
pfree(statedatums);
PG_RETURN_ARRAYTYPE_P(result);
}
/*
* Combine vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_combine);
Datum
vector_combine(PG_FUNCTION_ARGS)
{
ArrayType *statearray1 = PG_GETARG_ARRAYTYPE_P(0);
ArrayType *statearray2 = PG_GETARG_ARRAYTYPE_P(1);
float8 *statevalues1;
float8 *statevalues2;
float8 n;
float8 n1;
float8 n2;
int16 dim;
Datum *statedatums;
ArrayType *result;
/* Check arrays before using */
statevalues1 = CheckStateArray(statearray1, "vector_combine");
statevalues2 = CheckStateArray(statearray2, "vector_combine");
n1 = statevalues1[0];
n2 = statevalues2[0];
if (n1 == 0.0)
{
n = n2;
dim = STATE_DIMS(statearray2);
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
statedatums[i] = Float8GetDatumFast(statevalues2[i]);
}
else if (n2 == 0.0)
{
n = n1;
dim = STATE_DIMS(statearray1);
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
statedatums[i] = Float8GetDatumFast(statevalues1[i]);
}
else
{
n = n1 + n2;
dim = STATE_DIMS(statearray1);
CheckExpectedDim(dim, STATE_DIMS(statearray2));
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
{
double v = statevalues1[i] + statevalues2[i];
if (isinf(v))
float_overflow_error();
statedatums[i] = Float8GetDatumFast(v);
}
}
statedatums[0] = Float8GetDatumFast(n);
result = construct_array(statedatums, dim + 1,
FLOAT8OID,
sizeof(float8), FLOAT8PASSBYVAL, TYPALIGN_DOUBLE);
pfree(statedatums);
PG_RETURN_ARRAYTYPE_P(result);
}
/*
* Average vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_avg);
Datum
vector_avg(PG_FUNCTION_ARGS)
{
ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
float8 *statevalues;
float8 n;
uint16 dim;
Vector *result;
float v;
/* Check array before using */
statevalues = CheckStateArray(statearray, "vector_avg");
n = statevalues[0];
/* SQL defines AVG of no values to be NULL */
if (n == 0.0)
PG_RETURN_NULL();
/* Create vector */
dim = STATE_DIMS(statearray);
result = InitVector(dim);
for (int i = 0; i < dim; i++)
{
v = statevalues[i + 1] / n;
CheckElement(v);
result->x[i] = v;
}
PG_RETURN_POINTER(result);
}

View File

@@ -3,7 +3,11 @@
#include "postgres.h"
#define VECTOR_MAX_DIM 1024
#if PG_VERSION_NUM >= 160000
#include "varatt.h"
#endif
#define VECTOR_MAX_DIM 16000
#define VECTOR_SIZE(_dim) (offsetof(Vector, x) + sizeof(float)*(_dim))
#define DatumGetVector(x) ((Vector *) PG_DETOAST_DATUM(x))

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT ARRAY[1,2,3]::vector;
array
---------
@@ -24,6 +22,12 @@ SELECT ARRAY[1,2,3]::float8[]::vector;
[1,2,3]
(1 row)
SELECT ARRAY[1,2,3]::numeric[]::vector;
array
---------
[1,2,3]
(1 row)
SELECT '{NULL}'::real[]::vector;
ERROR: array must not containing NULLs
SELECT '{NaN}'::real[]::vector;
@@ -34,5 +38,18 @@ SELECT '{-Infinity}'::real[]::vector;
ERROR: infinite value not allowed in vector
SELECT '{}'::real[]::vector;
ERROR: vector must have at least 1 dimension
SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
ERROR: vector cannot have more than 1024 dimensions
SELECT '[1,2,3]'::vector::real[];
float4
---------
{1,2,3}
(1 row)
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
?column?
----------
t
(1 row)

View File

@@ -1,10 +1,8 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
CREATE TABLE t2 (val vector(3));
\copy t TO '/tmp/data.bin' WITH (FORMAT binary)
\copy t2 FROM '/tmp/data.bin' WITH (FORMAT binary)
\copy t TO 'results/data.bin' WITH (FORMAT binary)
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
SELECT * FROM t2 ORDER BY val;
val
---------

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT '[1,2,3]'::vector + '[4,5,6]';
?column?
----------
@@ -24,10 +22,28 @@ SELECT round(vector_norm('[1,1]')::numeric, 5);
1.41421
(1 row)
SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5);
round
---------
2.23607
SELECT vector_norm('[3,4]');
vector_norm
-------------
5
(1 row)
SELECT vector_norm('[0,1]');
vector_norm
-------------
1
(1 row)
SELECT l2_distance('[0,0]', '[3,4]');
l2_distance
-------------
5
(1 row)
SELECT l2_distance('[0,0]', '[0,1]');
l2_distance
-------------
1
(1 row)
SELECT l2_distance('[1,2]', '[3]');
@@ -40,10 +56,10 @@ SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1
SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5);
round
---------
0.00000
SELECT cosine_distance('[1,2]', '[2,4]');
cosine_distance
-----------------
0
(1 row)
SELECT cosine_distance('[1,2]', '[0,0]');
@@ -52,5 +68,37 @@ SELECT cosine_distance('[1,2]', '[0,0]');
NaN
(1 row)
SELECT cosine_distance('[1,1]', '[1,1]');
cosine_distance
-----------------
0
(1 row)
SELECT cosine_distance('[1,1]', '[-1,-1]');
cosine_distance
-----------------
2
(1 row)
SELECT cosine_distance('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
avg
-----------
[2,3.5,5]
(1 row)
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
avg
-----------
[2,3.5,5]
(1 row)
SELECT avg(v) FROM unnest(ARRAY[]::vector[]) v;
avg
-----
(1 row)
SELECT avg(v) FROM unnest(ARRAY['[1,2]'::vector, '[3]']) v;
ERROR: expected 2 dimensions, not 1

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT '[1,2,3]'::vector;
vector
---------
@@ -12,6 +10,12 @@ SELECT '[-1,2,3]'::vector;
[-1,2,3]
(1 row)
SELECT '[1.23456]'::vector;
vector
-----------
[1.23456]
(1 row)
SELECT '[hello,1]'::vector;
ERROR: invalid input syntax for type vector: "hello"
LINE 1: SELECT '[hello,1]'::vector;
@@ -53,3 +57,12 @@ LINE 1: SELECT '[1,]'::vector;
^
SELECT '[1,2,3]'::vector(2);
ERROR: expected 2 dimensions, not 3
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::vector[]);
unnest
---------
[1,2,3]
[4,5,6]
(2 rows)
SELECT '{"[1,2,3]"}'::vector(2)[];
ERROR: expected 2 dimensions, not 3

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));
CREATE INDEX ON t USING ivfflat (val) WITH (lists = 0);

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE UNLOGGED TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);

View File

@@ -0,0 +1,8 @@
use PostgreSQL::Test::Cluster;
sub get_new_node
{
return PostgreSQL::Test::Cluster->new(@_);
}
1;

3
test/perl/TestLib.pm Normal file
View File

@@ -0,0 +1,3 @@
use PostgreSQL::Test::Utils;
1;

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));

View File

@@ -1,13 +1,15 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT ARRAY[1,2,3]::vector;
SELECT ARRAY[1.0,2.0,3.0]::vector;
SELECT ARRAY[1,2,3]::float4[]::vector;
SELECT ARRAY[1,2,3]::float8[]::vector;
SELECT ARRAY[1,2,3]::numeric[]::vector;
SELECT '{NULL}'::real[]::vector;
SELECT '{NaN}'::real[]::vector;
SELECT '{Infinity}'::real[]::vector;
SELECT '{-Infinity}'::real[]::vector;
SELECT '{}'::real[]::vector;
SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
SELECT '[1,2,3]'::vector::real[];
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];

View File

@@ -1,13 +1,10 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE t (val vector(3));
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
CREATE TABLE t2 (val vector(3));
\copy t TO '/tmp/data.bin' WITH (FORMAT binary)
\copy t2 FROM '/tmp/data.bin' WITH (FORMAT binary)
\copy t TO 'results/data.bin' WITH (FORMAT binary)
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
SELECT * FROM t2 ORDER BY val;

View File

@@ -1,18 +1,26 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT '[1,2,3]'::vector + '[4,5,6]';
SELECT '[1,2,3]'::vector - '[4,5,6]';
SELECT vector_dims('[1,2,3]');
SELECT round(vector_norm('[1,1]')::numeric, 5);
SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5);
SELECT round(vector_norm('[1,1]')::numeric, 5);
SELECT vector_norm('[3,4]');
SELECT vector_norm('[0,1]');
SELECT l2_distance('[0,0]', '[3,4]');
SELECT l2_distance('[0,0]', '[0,1]');
SELECT l2_distance('[1,2]', '[3]');
SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]');
SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5);
SELECT cosine_distance('[1,2]', '[2,4]');
SELECT cosine_distance('[1,2]', '[0,0]');
SELECT cosine_distance('[1,1]', '[1,1]');
SELECT cosine_distance('[1,1]', '[-1,-1]');
SELECT cosine_distance('[1,2]', '[3]');
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
SELECT avg(v) FROM unnest(ARRAY[]::vector[]) v;
SELECT avg(v) FROM unnest(ARRAY['[1,2]'::vector, '[3]']) v;

View File

@@ -1,8 +1,6 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SELECT '[1,2,3]'::vector;
SELECT '[-1,2,3]'::vector;
SELECT '[1.23456]'::vector;
SELECT '[hello,1]'::vector;
SELECT '[NaN,1]'::vector;
SELECT '[Infinity,1]'::vector;
@@ -13,3 +11,6 @@ SELECT '1,2,3'::vector;
SELECT '[]'::vector;
SELECT '[1,]'::vector;
SELECT '[1,2,3]'::vector(2);
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::vector[]);
SELECT '{"[1,2,3]"}'::vector(2)[];

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE TABLE t (val vector(3));

View File

@@ -1,5 +1,3 @@
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS vector;
SET enable_seqscan = off;
CREATE UNLOGGED TABLE t (val vector(3));

View File

@@ -7,6 +7,8 @@ use PostgresNode;
use TestLib;
use Test::More tests => 31;
my $dim = 32;
my $node_primary;
my $node_replica;
@@ -18,25 +20,21 @@ sub test_index_replay
# Wait for replica to catch up
my $applname = $node_replica->name;
my $caughtup_query;
my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
if ($server_version_num >= 100000) {
$caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
} else {
# TODO figure out why replay location doesn't work
$caughtup_query = "SELECT pg_current_xlog_location() <= write_location FROM pg_stat_replication WHERE application_name = '$applname';";
}
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
$node_primary->poll_query_until('postgres', $caughtup_query)
or die "Timed out while waiting for replica 1 to catch up";
my $r1 = rand();
my $r2 = rand();
my $r3 = rand();
my @r = ();
for (1 .. $dim) {
push(@r, rand());
}
my $sql = join(",", @r);
my $queries = qq(SET enable_seqscan=off;
SELECT * FROM tst ORDER BY v <-> '[$r1,$r2,$r3]' LIMIT 10;
);
my $queries = qq(
SET enable_seqscan = off;
SELECT * FROM tst ORDER BY v <-> '[$sql]' LIMIT 10;
);
# Run test queries and compare their result
my $primary_result = $node_primary->safe_psql("postgres", $queries);
@@ -46,9 +44,21 @@ SELECT * FROM tst ORDER BY v <-> '[$r1,$r2,$r3]' LIMIT 10;
return;
}
# Use ARRAY[random(), random(), random(), ...] over
# SELECT array_agg(random()) FROM generate_series(1, $dim)
# to generate different values for each row
my $array_sql = join(",", ('random()') x $dim);
# Initialize primary node
$node_primary = get_new_node('primary');
$node_primary->init(allows_streaming => 1);
if ($dim > 32) {
# TODO use wal_keep_segments for Postgres < 13
$node_primary->append_conf('postgresql.conf', qq(wal_keep_size = 1GB));
}
if ($dim > 1500) {
$node_primary->append_conf('postgresql.conf', qq(maintenance_work_mem = 128MB));
}
$node_primary->start;
my $backup_name = 'my_backup';
@@ -63,12 +73,11 @@ $node_replica->start;
# Create ivfflat index on primary
$node_primary->safe_psql("postgres", "CREATE EXTENSION vector;");
$node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
$node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));");
$node_primary->safe_psql("postgres",
"INSERT INTO tst SELECT i%10, ARRAY[random(), random(), random()] FROM generate_series(1,100000) i;"
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
);
$node_primary->safe_psql("postgres",
"CREATE INDEX ON tst USING ivfflat (v);");
$node_primary->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
# Test that queries give same result
test_index_replay('initial');
@@ -82,7 +91,7 @@ for my $i (1 .. 10)
test_index_replay("vacuum $i");
my ($start, $end) = (100001 + ($i - 1) * 10000, 100000 + $i * 10000);
$node_primary->safe_psql("postgres",
"INSERT INTO tst SELECT i%10, ARRAY[random(), random(), random()] FROM generate_series($start,$end) i;"
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series($start, $end) i;"
);
test_index_replay("insert $i");
}

41
test/t/002_vacuum.pl Normal file
View File

@@ -0,0 +1,41 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 1;
my $dim = 3;
my @r = ();
for (1 .. $dim) {
my $v = int(rand(1000)) + 1;
push(@r, "i % $v");
}
my $array_sql = join(", ", @r);
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table and index
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
);
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
# Get size
my $size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
# Delete all, vacuum, and insert same data
$node->safe_psql("postgres", "DELETE FROM tst;");
$node->safe_psql("postgres", "VACUUM tst;");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
);
# Check size
my $new_size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
is($size, $new_size, "size does not change");

88
test/t/003_recall.pl Normal file
View File

@@ -0,0 +1,88 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 9;
my $node;
my @queries = ();
my @expected;
my $limit = 20;
sub test_recall
{
my ($probes, $min, $operator) = @_;
my $correct = 0;
my $total = 0;
for my $i (0 .. $#queries) {
my $actual = $node->safe_psql("postgres", qq(
SET enable_seqscan = off;
SET ivfflat.probes = $probes;
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
));
my @actual_ids = split("\n", $actual);
my %actual_set = map { $_ => 1 } @actual_ids;
my @expected_ids = split("\n", $expected[$i]);
foreach (@expected_ids) {
if (exists($actual_set{$_})) {
$correct++;
}
$total++;
}
}
cmp_ok($correct / $total, ">=", $min, $operator);
}
# Initialize node
$node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
);
# Generate queries
for (1..20) {
my $r1 = rand();
my $r2 = rand();
my $r3 = rand();
push(@queries, "[$r1,$r2,$r3]");
}
# Check each index type
my @operators = ("<->", "<#>", "<=>");
foreach (@operators) {
my $operator = $_;
# Get exact results
@expected = ();
foreach (@queries) {
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
push(@expected, $res);
}
# Add index
my $opclass;
if ($operator == "<->") {
$opclass = "vector_l2_ops";
} elsif ($operator == "<#>") {
$opclass = "vector_ip_ops";
} else {
$opclass = "vector_cosine_ops";
}
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v $opclass);");
# Test approximate results
test_recall(1, 0.75, $operator);
test_recall(10, 0.95, $operator);
test_recall(100, 1.0, $operator);
}

36
test/t/004_centers.pl Normal file
View File

@@ -0,0 +1,36 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 3;
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i, '[1,2,3]' FROM generate_series(1, 10) i;"
);
sub test_centers
{
my ($lists, $min) = @_;
my ($ret, $stdout, $stderr) = $node->psql("postgres", "CREATE INDEX ON tst USING ivfflat (v) WITH (lists = $lists);");
is($ret, 0, $stderr);
}
# Test no error for duplicate centers
test_centers(5);
test_centers(10);
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i, '[4,5,6]' FROM generate_series(1, 10) i;"
);
# Test no error for duplicate centers
test_centers(10);

View File

@@ -0,0 +1,45 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 60;
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4 primary key, v vector(3));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
);
# Check each index type
my @operators = ("<->", "<#>", "<=>");
foreach (@operators) {
my $operator = $_;
# Add index
my $opclass;
if ($operator == "<->") {
$opclass = "vector_l2_ops";
} elsif ($operator == "<#>") {
$opclass = "vector_ip_ops";
} else {
$opclass = "vector_cosine_ops";
}
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v $opclass);");
# Test 100% recall
for (1..20) {
my $i = int(rand() * 100000);
my $query = $node->safe_psql("postgres", "SELECT v FROM tst WHERE i = $i;");
my $res = $node->safe_psql("postgres", qq(
SET enable_seqscan = off;
SELECT v FROM tst ORDER BY v <-> '$query' LIMIT 1;
));
is($res, $query);
}
}

31
test/t/006_lists.pl Normal file
View File

@@ -0,0 +1,31 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 3;
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (v vector(3));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
);
$node->safe_psql("postgres", "CREATE INDEX lists50 ON tst USING ivfflat (v) WITH (lists = 50);");
$node->safe_psql("postgres", "CREATE INDEX lists100 ON tst USING ivfflat (v) WITH (lists = 100);");
# Test prefers more lists
my $res = $node->safe_psql("postgres", "EXPLAIN SELECT v FROM tst ORDER BY v <-> '[0.5,0.5,0.5]' LIMIT 10;");
like($res, qr/lists100/);
unlike($res, qr/lists50/);
# Test errors with too much memory
my ($ret, $stdout, $stderr) = $node->psql("postgres",
"CREATE INDEX lists10000 ON tst USING ivfflat (v) WITH (lists = 10000);"
);
like($stderr, qr/memory required is/);

55
test/t/007_inserts.pl Normal file
View File

@@ -0,0 +1,55 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 7;
my $dim = 768;
my $array_sql = join(",", ('random()') x $dim);
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table and index
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (v vector($dim));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
);
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
$node->pgbench(
"--no-vacuum --client=5 --transactions=100",
0,
[qr{actually processed}],
[qr{^$}],
"concurrent INSERTs",
{
"007_inserts" => "INSERT INTO tst SELECT ARRAY[$array_sql] FROM generate_series(1, 10) i;"
}
);
sub idx_scan
{
# Stats do not update instantaneously
# https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-VIEWS
sleep(1);
$node->safe_psql("postgres", "SELECT idx_scan FROM pg_stat_user_indexes WHERE indexrelid = 'tst_v_idx'::regclass;");
}
my $expected = 10000 + 5 * 100 * 10;
my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;");
is($count, $expected);
is(idx_scan(), 0);
$count = $node->safe_psql("postgres", qq(
SET enable_seqscan = off;
SET ivfflat.probes = 100;
SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t;
));
is($count, $expected);
is(idx_scan(), 1);

35
test/t/008_avg.pl Normal file
View File

@@ -0,0 +1,35 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 5;
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (r1 real, r2 real, r3 real, v vector(3));");
$node->safe_psql("postgres", qq(
INSERT INTO tst SELECT r1, r2, r3, ARRAY[r1, r2, r3] FROM (
SELECT random() + 1.01 AS r1, random() + 2.01 AS r2, random() + 3.01 AS r3 FROM generate_series(1, 1000000) t
) i;
));
# Test avg
my $avg = $node->safe_psql("postgres", "SELECT AVG(v) FROM tst;");
like($avg, qr/\[1\.5/);
like($avg, qr/,2\.5/);
like($avg, qr/,3\.5/);
# Test matches real
my $r1 = $node->safe_psql("postgres", "SELECT AVG(r1)::float4 FROM tst;");
my $r2 = $node->safe_psql("postgres", "SELECT AVG(r2)::float4 FROM tst;");
my $r3 = $node->safe_psql("postgres", "SELECT AVG(r3)::float4 FROM tst;");
is($avg, "[$r1,$r2,$r3]");
# Test explain
my $explain = $node->safe_psql("postgres", "EXPLAIN SELECT AVG(v) FROM tst;");
like($explain, qr/Partial Aggregate/);

32
test/t/009_storage.pl Normal file
View File

@@ -0,0 +1,32 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 1;
my $dim = 1024;
# Initialize node
my $node = get_new_node('node');
$node->init;
$node->start;
# Create table
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (v1 vector(1024), v2 vector(1024), v3 vector(1024));");
# Test insert succeeds
$node->safe_psql("postgres",
"INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
);
# Change storage to PLAIN
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v1 SET STORAGE PLAIN");
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v2 SET STORAGE PLAIN");
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v3 SET STORAGE PLAIN");
# Test insert fails
my ($ret, $stdout, $stderr) = $node->psql("postgres",
"INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
);
like($stderr, qr/row is too big/);

View File

@@ -1,4 +1,4 @@
comment = 'vector data type and ivfflat access method'
default_version = '0.1.7'
default_version = '0.4.1'
module_pathname = '$libdir/vector'
relocatable = true