有没有更好的方法来编写这个 Postgres JSONB 查询?

Is there a better way to write this Postgres JSONB query?

下面是一个示例 JSONB 数组。我正在尝试弄清楚如何编写不需要像这样的叉积的查询。

select b.id from brand b,jsonb_array_elements (b.tree) a where a#>>'{Name}'  = 'Skiing';

帮助我将其翻译成 SQL Alchemy

的奖励积分
[
  {
    "Name": "Snowboarding",
    "Order": 1,
    "Categories": {
      "Jackets": [
        22002,
        23224
      ],
      "Helmets": [
        24920
      ],
      "Freestyle Boards": [
        20164
      ],
      "Goggles": [
        23169,
        23280
      ],
      "Hats": [
        22966,
        21727
      ],
      "Bindings": [
        19265
      ],
      "Gloves": [
        20461
      ],
      "Boots": [
        26374,
        19079,
        21765,
        22669
      ],
      "Freeride Boards": [
        18395,
        25505
      ],
      "Pants": [
        24143,
        20957
      ]
    }
  },
  {
    "Name": "Skiing",
    "Order": 2,
    "Categories": {
      "Jackets": [
        22518,
        25791,
        19972
      ],
      "Pants": [
        17516,
        23113
      ],
      "Goggles": [
        25066,
        20996
      ],
      "Helmets": [
        24378
      ],
      "Hats": [
        20009,
        21245
      ],
      "Cross-country Skiing": [
        17464
      ],
      "Gloves": [
        25822
      ],
      "Boots": [
        16616
      ],
      "Poles": [
        19280
      ]
    }
  },....]

SQL 先解决:

SELECT  brand.id
FROM    brand
WHERE   brand.tree @> '[{"Name": "Skiing"}]'::jsonb;

至于sqlalchemy版本,您可以简单地使用contains来生成上面的SQL语句:

q = (session.query(Brand.id)
     .filter(Brand.tree.contains([{"Name": "Skiing"}]))
     )