需求场景:html
目录以jsonb格式存储在数据库表t的chapter字段中,须要菜单路径中包含指定字符串(好比“语文”或者“上学期”)的menusql
如下为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):json
SELECT chapter FROM t WHERE chapter #>>'{menu,text}'like '%语文%'
对应mybatis mapper配置文件:
<if test="chapter != null and chapter!= ''"> chapter #>>'{menu,text}' LIKE concat('%',#{chapter},'%') </if>
优化(建立全文索引):mybatis
CREATE INDEX i_chapter_text_jsonb_gin ON resource USING gin((chapter #>>'{menu,text}') gin_trgm_ops);
建立索引可能会遇到的问题:app
1.ERROR: operator class "gin_trgm_ops" does not exist for access method "gin"post
解决方案:优化
先执行 CREATE EXTENSION pg_trgm;spa
2.ERROR: could not open extension control file "/usr/pgsql-9.6/share/extension/pg_trgm.control": No such file or directory.net
解决方案:
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
另外关于索引能够参考(一篇大杂烩):