postgresql模糊查詢json類型字段內某一屬性值

需求場景: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

另外關於索引能夠參考(一篇大雜燴):

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

相關文章
相關標籤/搜索