英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论