你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

教程:使用 Azure Database for PostgreSQL 和 Azure OpenAI 创建语义搜索

适用于: Azure Database for PostgreSQL 灵活服务器

本动手教程介绍如何使用 Azure Database for PostgreSQL 和 Azure OpenAI 生成语义搜索应用程序。

语义搜索基于语义进行搜索。 标准词法搜索基于查询中提供的关键字进行搜索。 例如,食谱数据集可能不包含无麸质、素食、无乳制品、无水果或甜点等标签,但这些特征可以从成分中推断出来。 其思路是发出此类语义查询并获取相关的搜索结果。

在本教程中,你将:

  • 确定将在搜索中涉及的搜索方案和数据字段。
  • 对于搜索中涉及的每个数据字段,请创建相应的向量字段来存储存储在数据字段中的值的嵌入。
  • 为所选数据字段中的数据生成嵌入,并将嵌入存储在其相应的矢量字段中。
  • 为任何输入搜索查询生成嵌入。
  • 搜索矢量数据字段并列出最近的邻域。
  • 通过适当的相关性、排名和个性化模型运行结果,以生成最终排名。 如果没有此类模型,则按点积递减顺序对结果进行排名。
  • 监视模型、结果质量和业务指标,例如点击率和停留时间。 结合反馈机制来调试和改进搜索堆栈,从数据质量、数据新鲜度和个性化到用户体验。

Prerequisites

  1. 创建 OpenAI 帐户并请求访问 Azure OpenAI
  2. 在所需订阅中授予对 Azure OpenAI 的访问权限。
  3. 授予创建 Azure OpenAI 资源和部署模型的权限。
  4. 创建和部署 Azure OpenAI 资源和模型。 部署嵌入模型 文本嵌入-ada-002。 复制部署名称,因为需要使用它来创建嵌入。

启用 azure_ai 和 pgvector 扩展

在 Azure Database for PostgreSQL 灵活服务器上启用 azure_aipgvector 之前,需要先将它们加入允许列表。 确保通过运行 SHOW azure.extensions; 来正确添加它们。

然后,可以通过连接到目标数据库并运行 CREATE EXTENSION 命令来安装扩展。 对于希望扩展可用的每个数据库,需要单独重复该命令。

CREATE EXTENSION azure_ai;
CREATE EXTENSION vector;

配置 OpenAI 终结点和密钥

在 Azure AI 服务中的 “资源管理>密钥和终结点”下,可以找到 Azure AI 资源的终结点和密钥。 使用终结点和其中一个密钥来启用azure_ai扩展,从而调用模型部署:

select azure_ai.set_setting('azure_openai.endpoint','https://<endpoint>.openai.azure.com');
select azure_ai.set_setting('azure_openai.subscription_key', '<API Key>');

下载数据

Kaggle 下载数据。

创建表

连接到服务器并创建 test 数据库。 在该数据库中,使用以下命令创建要在其中导入数据的表:

CREATE TABLE public.recipes(
    rid integer NOT NULL,
    recipe_name text,
    prep_time text,
    cook_time text,
    total_time text,
    servings integer,
    yield text,
    ingredients text,
    directions text,
    rating real,
    url text,
    cuisine_path text,
    nutrition text,
    timing text,
    img_src text,
    PRIMARY KEY (rid)
);

导入数据

在客户端窗口中设置以下环境变量,将编码设置为 UTF-8。 此步骤是必需的,因为此特定数据集使用 Windows-1252 编码。

Rem on Windows
Set PGCLIENTENCODING=utf-8;
# on Unix based operating systems
export PGCLIENTENCODING=utf-8

将数据导入到创建的表中。 请注意,此数据集包含标题行。

psql -d <database> -h <host> -U <user> -c "\copy recipes FROM <local recipe data file> DELIMITER ',' CSV HEADER"

添加一个列来存储嵌入

向表添加嵌入列:

ALTER TABLE recipes ADD COLUMN embedding vector(1536);

生成嵌入内容

使用 azure_ai 扩展为数据生成嵌入。 以下示例向量化几个字段并连接。

WITH ro AS (
    SELECT ro.rid
    FROM
        recipes ro
    WHERE
        ro.embedding is null
        LIMIT 500
)
UPDATE
    recipes r
SET
    embedding = azure_openai.create_embeddings('text-embedding-ada-002', r.recipe_name||' '||r.cuisine_path||' '||r.ingredients||' '||r.nutrition||' '||r.directions)
FROM
    ro
WHERE
    r.rid = ro.rid;

重复该命令,直到没有更多行要处理。

提示

尝试调整LIMIT值。 如果使用的值较高,该语句可能因 Azure OpenAI 施加的限制而中途失败。 如果语句失败,请等待至少一分钟,然后再次运行该命令。

为方便起见,请在数据库中创建搜索函数:

create function
    recipe_search(searchQuery text, numResults int)
returns table(
            recipeId int,
            recipe_name text,
            nutrition text,
            score real)
as $$
declare
    query_embedding vector(1536);
begin
    query_embedding := (azure_openai.create_embeddings('text-embedding-ada-002', searchQuery));
    return query
    select
        r.rid,
        r.recipe_name,
        r.nutrition,
        (r.embedding <=> query_embedding)::real as score
    from
        recipes r
    order by score asc limit numResults; -- cosine distance
end $$
language plpgsql;

现在只需调用函数进行搜索:

select recipeid, recipe_name, score from recipe_search('vegan recipes', 10);

浏览结果:

 recipeid |                         recipe_name                          |   score
----------+--------------------------------------------------------------+------------
      829 | Avocado Toast (Vegan)                                        | 0.15672222
      836 | Vegetarian Tortilla Soup                                     | 0.17583494
      922 | Vegan Overnight Oats with Chia Seeds and Fruit               | 0.17668104
      600 | Spinach and Banana Power Smoothie                            |  0.1773768
      519 | Smokey Butternut Squash Soup                                 | 0.18031077
      604 | Vegan Banana Muffins                                         | 0.18287598
      832 | Kale, Quinoa, and Avocado Salad with Lemon Dijon Vinaigrette | 0.18368931
      617 | Hearty Breakfast Muffins                                     | 0.18737361
      946 | Chia Coconut Pudding with Coconut Milk                       |  0.1884186
      468 | Spicy Oven-Roasted Plums                                     | 0.18994217
(10 rows)