使用SQLAlchemy如何对两个数组进行交集操作

huangapple go评论52阅读模式
英文:

How to make an intersection of two arrays using sqlalchemy

问题

在PostgreSQL中,我可以执行以下操作:

SELECT * FROM posts
WHERE string_to_array(lower(title), ' ') && array['my']

但我不知道如何在SQLAlchemy ORM中执行此操作。我有一个与数据库的异步连接:

engine = create_async_engine(config.ASYNC_SQLALCHEMY_URL, echo=True)

async_session = async_sessionmaker(
    engine, class_=AsyncSession, expire_on_commit=False
)

async def get_async_session() -> AsyncSession:
    async with async_session() as session:
        yield session
        await session.commit()

各位,你们知道吗?

我在SQLAlchemy文档和互联网上找到了相关信息。

英文:

In postgresql i can do this

SELECT * FROM posts
WHERE string_to_array(lower(title), ' ') && array['my']

but i do not know and can't find how to do this using sqlalchemy orm. I have async connection to a database

engine = create_async_engine(config.ASYNC_SQLALCHEMY_URL, echo=True)


async_session = async_sessionmaker(
    engine, class_=AsyncSession, expire_on_commit=False
)


async def get_async_session() -> AsyncSession:
    async with async_session() as session:
        yield session
        await session.commit()

Guys do you know?

I found in the sqlalchemy documentation and in the Internet

答案1

得分: 1

你可以通过调用string_to_array的输出上的&&操作来执行此操作,并将第二个数组作为此调用的参数传递,如下所示:

import sqlalchemy as sa

q = sa.select(tbl.c.col).where(
    sa.func.string_to_array(sa.func.lower(tbl.c.col), ' ').op('&&')(['my'])
)

此示例使用同步连接,但对于同步或异步连接,select查询本身完全相同。

import sqlalchemy as sa

strings = [
    'In my house',
    'My shoes',
    'Amy Parker',
    'Captain Obvious',
]

engine = sa.create_engine('postgresql:///test', echo=False)

with engine.connect() as conn:
    for string in strings:
        res = conn.execute(
            sa.select(sa.literal(string)).where(
                sa.func.string_to_array(
                    sa.func.lower(sa.literal(string)), ' '
                ).op('&&')(['my'])
            )
        )
        print(res.fetchone())

输出:

('In my house',)
('My shoes',)
None
None
英文:

You can do this by calling the && operation on the output of string_to_array, and passing the second array as the argument to this call, like this:

import sqlalchemy as sa

q = sa.select(tbl.c.col).where(
    sa.func.string_to_array(sa.func.lower(tbl.c.col), ' ').op('&&')(['my'])
)

This example uses a synchronous connection, but the select query itself is exactly the same for synchronous or asynchronous connections.

import sqlalchemy as sa

strings = [
    'In my house',
    'My shoes',
    'Amy Parker',
    'Captain Obvious',
]

engine = sa.create_engine('postgresql:///test', echo=False)

with engine.connect() as conn:
    for string in strings:
        res = conn.execute(
            sa.select(sa.literal(string)).where(
                sa.func.string_to_array(
                    sa.func.lower(sa.literal(string)), ' '
                ).op('&&')(['my'])
            )
        )
        print(res.fetchone())

Output

('In my house',)
('My shoes',)
None
None

huangapple
  • 本文由 发表于 2023年2月24日 00:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定