使用 SQLAlchemy/Flask SQLAlchemy 从 PostgreSQL JSON 字段中选择数据

Selecting data from PostgreSQL JSON field with SQLAlchemy / Flask SQLAlchemy

我的JSON在数据库中是这样的:

{
    "ingredients": [
        "3 tablespoons almond butter",
        ...
        "Lime wedges"
    ],
    "instructions": [
        "In a bowl" 
    ]
    "tags": [
        "gluten-free",
        "grain bowls",
        "Thai"
     ]
}

我的 app.py 文件:

class Recipe(db.Model):
    __tablename__ = "recipe"
    ....
    recipe = db.Column(db.JSON)

首先,我正在尝试 select 所有带有“泰国”标签的记录。

Recipe.query.filter(Recipe.recipe['tags'].contains(["Thai"])).all()

告诉我我可能需要显式类型转换,我已经尝试过 astext 和 cast.. 似乎没有任何效果。不确定我做错了什么。

这里是堆栈跟踪的结尾:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: json ~~ text
LINE 3: WHERE ((recipe.recipe -> 'tags') LIKE '%' || CAST('["%Thai%"...
                                         ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

[SQL: SELECT recipe.id AS recipe_id, recipe.url_id AS recipe_url_id, recipe.author AS recipe_author, recipe.description AS recipe_description, recipe.recipe AS recipe_recipe 
FROM recipe 
WHERE ((recipe.recipe -> %(recipe_1)s) LIKE '%%' || CAST(%(param_1)s AS JSON) || '%%')]
[parameters: {'recipe_1': 'tags', 'param_1': '["%Thai%"]'}]

我试过:

Recipe.query.filter(Recipe.recipe['tags'].contains(cast(["%Thai%"], JSON)))

有效的是

db.engine.execute(text("select * from recipe where recipe->> 'tags' like '%Thai%'"))

我可以接受,但我顽固地希望它通过 ORM 发生。

我唯一的线索是,在堆栈跟踪中,我看到它生成了一个 sql 语句,其中 -> 不是 ->> ...但我不知道如何获得 - >>

然后我发现了这个:

tags_subquery = db.session.query(func.json_array_elements(Recipe.recipe['tags']).label('tags')).subquery()
query = db.session.query(Recipe, tags_subquery.c.tags).filter(tags_subquery.c.tags.op('->>')('tags').like("%Thai%"))

没有错误,但结果是空的...我想我现在有点接近了感谢@r-m-n

您可以通过将表达式的左侧转换为文本类型来避免错误:

# select cast('{"a": ["spam", "ham"]}'::json->'a' as text) like '%spam%' as "Exists?";
 Exists? 
═════════
 t

但这也将匹配子字符串,这可能是不可取的:

# select cast('{"a": ["spam", "ham"]}'::json->'a' as text) like '%am%' as "Exists?";
 Exists? 
═════════
 t

更好的选择是转换为 jsonb:

# select cast('{"a": ["spam", "ham"]}'::json->'a' as jsonb) @> '["spam"]' as "Exists?";
 Exists? 
═════════
 t
 
# select cast('{"a": ["spam", "ham"]}'::json->'a' as jsonb) @> '["am"]' as "Exists?";
 Exists? 
═════════
 f

在 Python 方面,这看起来像

from sqlalchemy import cast
from sqlalchemy.dialects.postgresql import JSONB

result = Recipe.query.filter(
    cast(Recipe.recipe['tags'], JSONB).contains(["Thai"])
).all()

将列类型更改为 JSONB 将不再需要转换(但需要迁移):

class Recipe(db.Model)
    ...
    recipe = sb.Column(JSONB)

result = Recipe.filter(Recipe.recipe['tags'].contains(['Thai'])).all()

您可以在 source.

中看到 JSON(B) 比较方法如何映射到 Postgresql 函数