为啥要用到数组类型呢?因为ES支持数组类型,为了迁移遍历,所以也支持数组类型。
select docid,authors from search_doc_new_ic where authors @>'{"惠普"}' limit 10; docid |authors | --------------------------------+---------------+ cc88a182e84f4ab2a976abe1cbba0b41|{王玮嘉,惠普,黄波,环保Ⅱ}| c3826da7a322490296ec9c5901ba353a|{王玮嘉,惠普,黄波} | fc4f63dec47b4facb8216d8b29d9918a|{王玮嘉,惠普,黄波} | 863afb11385848c9a8a7c5df51024532|{王玮嘉,惠普,黄波,环保Ⅱ}| fdc0562295304045b5c7ce940f96d56b|{王玮嘉,惠普,黄波,环保Ⅱ}| 6073e0de9b2747359c9b02e9bf0a9c2b|{王玮嘉,惠普,黄波} | facc9518c75148da8b079fde64f47691|{王玮嘉,惠普,黄波} | 7c587a6337aa40c3acdbe7e363575317|{王玮嘉,惠普,黄波} | dcf807b2b0cc477ca7919cc41d9f5331|{王玮嘉,惠普,黄波} | 631c4dd57afa40a694be1720e1b4a865|{王玮嘉,惠普,黄波} |
SELECT * FROM sal_emp; name |pay_by_quarter |schedule | -----+-------------------------+-----------------------------------------+ Bill |{10000,10000,10000,10000}|{{meeting,lunch},{training,presentation}}| Carol|{20000,25000,25000,25000}|{{breakfast,consulting},{meeting,lunch}} |
SELECT * FROM sal_emp where 15000 < any (pay_by_quarter); -- 查询pay_by_quarter数组中任何一个元素都大于15000 name |pay_by_quarter |schedule | -----+-------------------------+----------------------------------------+ Carol|{20000,25000,25000,25000}|{{breakfast,consulting},{meeting,lunch}}|
SELECT * FROM sal_emp where 22500 > ALL (pay_by_quarter); -- 查询pay_by_quarter数组中任何一个元素都小于22500 name|pay_by_quarter |schedule | ----+-------------------------+-----------------------------------------+ Bill|{10000,10000,10000,10000}|{{meeting,lunch},{training,presentation}}|
SELECT * FROM sal_emp where array_to_string(schedule,',') like '%sult%'; -- 数组模糊查询 name |pay_by_quarter |schedule | -----+-------------------------+----------------------------------------+ Carol|{20000,25000,25000,25000}|{{breakfast,consulting},{meeting,lunch}}|
访问JSON中的数组
create table test_ft(id int4,arry VARCHAR[],content1 jsonb,body text); insert into test_ft values(1,ARRAY [ 'x', 'y' ],'{ "guid": "9c36adc1-7fb5-4d5b-83b4-90356a46balabala", "name": "james", "is_active": true, "company": "Oracle", "address": "178 Howard Place, Gulf, Washington, 702", "registered": "2009-11-07T08:53:22 +08:00", "latitude": 19.793713, "longitude": 86.513373, "tags": [ "enim", "aliquip", "qui" ]}','postgresql支持两种json数据类型:json和jsonb,而两者唯一的区别在于效率,json是对输入的完整拷贝,使用时再去解析,所以它会保留输入的空格,重复键以及顺序等。而jsonb是解析输入后保存的二进制,它在解析时会删除不必要的空格和重复的键,顺序和输入可能也不相同。使用时不用再次解析。两者对重复键的处理都是保留最后一个键值对。效率的差别:json类型存储快,使用慢,jsonb类型存储稍慢,使用较快。');
select id,arry, content1->'name',substr(body,1,100) from test_ft t where t.arry @>'{"x"}' and t.content1 @>'{"name":"james"}' and t.content1->'tags'->>1='aliquip' -- 访问content1 JSON中tags数组元素的第一个值
java到pg array的映射参见https://www.2ndquadrant.com/en/blog/using-java-arrays-to-insert-retrieve-update-postgresql-arrays/
https://www.postgresql.org/docs/current/functions-array.html