1.操作键值对
PostgreSQL 对 jsonb 类型的筛选查询可以使用 ->
或者 ->>
操作符。
->
操作符用于通过 JSON 对象中的键来获取对应的值。->>
操作符可以将获取到的值提取出来转化为字符串类型。
例如,下面是一个包含 jsonb 类型字段的表:
CREATE TABLE test ( id SERIAL PRIMARY KEY, data JSONB ); INSERT INTO test (data) VALUES ('{"name": "John", "age": 30, "city": "New York"}'); INSERT INTO test (data) VALUES ('{"name": "Jane", "age": 25, "city": "Los Angeles"}');
我们可以通过下面这中查询方式进行全库的全文检索查询
-- 获取所有数据 SELECT * FROM test; -- 根据 jsonb 字段中的键值进行查询 SELECT * FROM test WHERE data -> 'name' = '"John"'; -- 注意:键名需要用单引号括起来,并且值需要用双引号括起来。 -- 使用 ->> 将键对应的值提取出来进行查询 SELECT * FROM test WHERE data ->> 'age' = '30';
上面这个提取出来的例子可能不明显
下面添加一个复杂的json例子
{ "caseInfo": { "caseNo": "C20xxxxxxxxx8212566", "reportNo": "P2xxxxxxxxxxxxxxxxx3004", "applyTime": 17xxxxxxxxx5000, "companyId": 1xx00, "treatType": "1", "createFrom": 1xxx1, "companyName": "中国xxxxxxxxxxx公司", "processType": "2xx", "accidentDate": 171xxxxxxxx1000, "accidentType": "xx1x", "hospitalCode": "xxxxxxxxx35", "hospitalName": "台xxxxxxxxxxxx院", "hospitalLevel": "", "medicalFinish": "", "firstCompanyId": 0987654, "injuredFromArea": "ytgrefds", "insuranceTypeId": "", "firstCompanyName": "中xxxxxxxxxxxx限公司", "hospitalAttribute": "", "uploadUserOrgCode": "", "totalSettlementAmount": 0 }, "patientInfo": { "name": "邱76y5t432", "idCard": "33sacdvfgbdcs1232675", "address": "asadfghfdsa村", "birthday": sadcsxazxsc000, "cardType": "asdsad", "idDueDay": 2asxcv bgdfsc000, "genderCode": "1" }, "applyUserInfo": { "nationality": "CHN", "applyUserName": "", "applyUserIdCard": "", "applyUserBirthday": "", "applyUserCardType": "", "applyUserIdDueDay": "", "applyUserGenderCode": "", "applyUserPatientRelation": "" } }
这个时候提取的作用就显得明显了很多
-- ->> 提取测试sql,将applyUserInfo下的nationality提取出来,做一维sql标准查询 SELECT count(*) FROM case_service.cs_case_model WHERE (cs_case_model.case_model_detail -> 'applyUserInfo' ->> 'nationality') like '%C%';
结果: