需求場景:
目錄以jsonb格式存儲在數據庫表t的chapter字段中,需要菜單路徑中包含指定字符串(比如“語文”或者“上學期”)的menu
以下為chapter字段存儲json示例:
{
"menu": {
"text": "第一級菜單(語文)>第二級菜單(上學期)>第三級菜單(第一章節)",
"menuItem": [
{
"root": true,
"id": "1",
"pId": "",
"text": "第一級菜單(語文)"
},
{
"root": false,
"id": "2",
"pId": "1",
"text": "第二級菜單(上學期)"
},
{
"root": false,
"id": "3",
"pId": "2",
"text": "第三級菜單(第一章節)"
}
]
}
}
實現(有關postgresql json類型支持的操作符可以參考:官方文檔,https://blog.csdn.net/u012129558/article/details/81453640):
SELECT chapter FROM t WHERE chapter #>>'{menu,text}'like '%語文%'
對應mybatis mapper配置文件:
<if test="chapter != null and chapter!= ''"> chapter #>>'{menu,text}' LIKE concat('%',#{chapter},'%') </if>
優化(創建全文索引):
CREATE INDEX i_chapter_text_jsonb_gin ON resource USING gin((chapter #>>'{menu,text}') gin_trgm_ops);
創建索引可能會遇到的問題:
1.ERROR: operator class "gin_trgm_ops" does not exist for access method "gin"
解決方案:
先執行 CREATE EXTENSION pg_trgm;
2.ERROR: could not open extension control file "/usr/pgsql-9.6/share/extension/pg_trgm.control": No such file or directory
解決方案:
https://dba.stackexchange.com/questions/165300/how-to-install-the-additional-module-pg-trgm
Ubuntu/Debian: sudo apt install postgresql-contrib Redhat/Centos sudo dnf install postgresql10-contrib
另外關於索引可以參考(一篇大雜燴):