代码之家  ›  专栏  ›  技术社区  ›  Ingo Bürk

postgresql:json数组中的过滤器

  •  0
  • Ingo Bürk  · 技术社区  · 6 年前

    假设我们有一张桌子 items 有柱子的 name attributes :

    CREATE TABLE students (
      name VARCHAR(100),
      attributes JSON
    )
    

    其中,属性是一组(始终结构相同)JSON文档,例如

    [{"name":"Attribute 1","value":"Value 1"},{"name":"Attribute 2","value":"Value 2"}]
    

    现在我要查找所有属性值与某个值匹配的学生(例如 Foo% ) Here's a playground example .

    我意识到这并不是最直接的设计,但现在我必须要做的是,尽管这样一个搜索的性能明显非常低效当然是一个值得关注的问题。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Kaushik Nayak    6 年前

    您可以使用 json_array_elements 要访问元素,然后使用->>json运算符使用某个值进行搜索。

    select s.*,j from 
      students  s 
       cross join lateral json_array_elements ( attributes ) as j
    WHERE j->>'value' like 'Foo%'
    

    Demo

    编辑

    现在的问题是交叉联接将“复制”行。是 有更好的方法来避免这种情况

    使用 WITH ORDINALITY 生成每个元素的ID,然后使用 DISTINCT ON 获得每个学生的第一个/最后一个匹配。

    select DISTINCT ON (name) s.*,j.attr from 
    students  s 
    cross join lateral json_array_elements ( attributes ) WITH ORDINALITY as j(attr,id)
    WHERE j.attr->>'value' like 'Value%'
    ORDER BY name,j.id
    

    Demo2