首页 > 数据库技术 > 详细

postgresql模糊查询json类型字段内某一属性值

时间:2019-02-16 11:14:37      阅读:496      评论:0      收藏:0      [点我收藏+]

需求场景:

目录以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

另外关于索引可以参考(一篇大杂烩):

https://juejin.im/entry/586b448761ff4b00578c1b7a

postgresql模糊查询json类型字段内某一属性值

原文:https://www.cnblogs.com/goingforward/p/10386979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!