本页介绍了如何使用 AlloyDB AI 查询引擎提供的运算符函数在 SQL 运算符中使用自然语言。您可以使用 ai.if
、Join 与 ai.if
、ai.score
和 ai.generate
运算符将自然语言与 SQL 查询结合使用。
如需使用本页中的说明,您必须了解 AlloyDB for PostgreSQL 并熟悉生成式 AI 概念。
AlloyDB 会预留 ai
架构,并在您安装 google_ml_integration
扩展程序时尝试创建此架构。如果架构创建失败,请在 google_ml
架构中使用同名函数。
准备工作
- 申请使用自然语言使用 SQL 运算符的权限,然后等待收到启用确认,然后再按照本页中的说明操作。
在查询中使用过滤条件和联接
如需评估是否满足以自然语言陈述的条件,请使用 ai.if
/google_ml.if
运算符。该函数会返回布尔值 true 或 false,如果无法明确检测到输出,则返回 NULL。
以下示例查询展示了如何查找提及停车位的餐厅评价。
SELECT review AS talks_about_parking
FROM user_reviews
WHERE
ai.if(
prompt => 'the following review talks about parking at the restaurant. review: ' || review);
执行联接操作
如需执行联接运算,请将 ai.if
/google_ml.if
运算符与联接结合使用。以下示例查询会查找提及餐厅菜单中每个菜品的评价数量。
SELECT item_name, COUNT(*)
FROM menu_items JOIN user_reviews
ON ai.if(
prompt => 'Does the following user review talk about the menu item mentioned ? review: ' || user_reviews.review_text || ' menu item: ' || item_name)
GROUP BY item_name;
为查询结果评分
如需根据使用自然语言陈述的语义条件对查询中的项列表进行排序,请使用 ai.rank/google_ml.rank
运算符
以下示例查询会获取前 20 条最正面的餐厅评价。它会根据 ai.rank/google_ml.rank
函数调用中设置的条件对响应进行排序。
SELECT review AS top20
FROM user_reviews
ORDER BY ai.rank('Score the following review according to these rules: score of 8 to 10 if the review says the food is excellent, 4 to 7 if the review says the food is and 1 to 3 if the review says the food is not good. Here is the review: ' || review)
LIMIT 20;
使用自然语言为 SQL 运算符生成文本
如需根据自然语言指定的提示生成文本,请使用 ai.generate
/google_ml.generate
函数。
以下查询会根据 ai.generate
函数调用中指定的条件生成每条用户评价的摘要。
SELECT
ai.generate(
prompt => 'Summarize the review in 20 words or less. Review: ' || review_text) AS review_summary
FROM user_reviews;