你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Note
Foundry IQ (Azure AI 搜索) 提供直接索引和查询 API 以及用于托管检索的高级知识库和知识库 API。 使用 Azure 门户、REST API 或 Azure SDK 来配置这些功能,或者在 Microsoft Foundry 门户中将智能体连接到知识库。
Important
实体图目前处于公共预览版,并受 Microsoft Azure 预览版补充使用条款约束。 有关此功能特有的预览条款,请参阅预览功能。
实体图(预览)将人员、组织、地点和其他概念表示为节点,并将它们之间的关系表示为边。 它可以回答依赖于实体之间关联的问题,例如哪些人在某个特定城市的组织工作。
在 Foundry IQ(Azure AI 搜索)中,图谱提取会将 Blob 内容转换为实体图谱。 创建支持图谱的 Blob 知识源,然后通过知识库或直接使用 GQL 查询托管图谱。 与主题图不同,实体图会基于本体捕获显式实体及其关系。
Prerequisites
- 一个支持
2026-11-01-previewREST API 的 Foundry IQ 服务。 - Python 示例需要 Python 3.10 或更高版本,C# 示例需要 .NET 8 或更高版本。
- 对于 SDK 示例,请按照创建知识库中的公共源预览包说明操作。
- Blob 知识源的服务、模型部署、身份验证和计费先决条件。
- 包含文本内容的Azure Blob 存储容器。 此图形工作流不支持 ADLS Gen2、ACL 摄取或敏感度标签摄取。
- 在首次编制索引运行之前,已启用本机 Blob 软删除。 必须禁用 Blob 版本控制。
- 引入聊天补全模型。 知识库需要有自己的模型配置,以支持自然语言的图查询。
- 创建和删除测试知识源和知识库的权限。 为这些示例配置 无密钥身份验证 。 有关查询权限和 SDK 示例使用的 Azure Identity 库,请参阅查询知识库的先决条件。
Limitations
实体图检索需要新的知识库。 不能对现有知识库启用实体图检索。
实体图功能在此版本中仅限 API。 可以使用内置 UI 作为 Foundry IQ 技能插件的一部分。
最佳做法
- 使用 Foundry IQ 技能插件 作为推荐的入门方式。 若要使用 REST API 或 SDK 进行直接设置,请按照本文中的步骤操作。
- 使用
gpt-5.6-luna低检索推理工作量,以获得最佳质量和成本平衡。 - 围绕你预计用户会向知识库提出的关键问题设计本体。 本体的质量决定了图形的形状和内容,因此包括这些问题所需的实体类型和关系。
- 从一个关键用例和一组少量实体类型和关系开始。 在扩大规模之前,请用有代表性的查询验证提取出的图。
- 请同时根据语料库规模以及提取出的实体和关系数量来估算图构建成本。
- 在预览期间,实体图功能本身无需额外付费。 仍需为所使用的模型令牌付费。
准备内容和本体
本体定义要提取的实体类型和关系。 围绕你期望用户提出的问题进行设计。 此示例中使用了人员、其雇主以及这些雇主所在的城市。
将以下虚构内容上传到容器中命名
roster.txt的文本 Blob。Avery Chen works for Contoso Robotics. Contoso Robotics is located in Seattle. Jordan Davis works for Fabrikam Analytics. Fabrikam Analytics is located in Austin.上传名为 的第二个文本 blob。 它为西雅图关系提供了另一个源断言。
Avery Chen is employed by Contoso Robotics, an organization located in Seattle.将本体定义为一个受限的 JSON-LD 文档。 命名空间标识您的应用程序术语;此示例定义
Person、Organization、Place、worksFor和locatedIn。{ "@context": { "owl": "http://www.w3.org/2002/07/owl#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "ex": "https://schema.search.azure.com/entities#" }, "@graph": [ { "@id": "ex:Person", "@type": "owl:Class", "rdfs:comment": "A person." }, { "@id": "ex:Organization", "@type": "owl:Class", "rdfs:comment": "An organization." }, { "@id": "ex:Place", "@type": "owl:Class", "rdfs:comment": "A geographic place." }, { "@id": "ex:worksFor", "@type": "owl:ObjectProperty", "rdfs:domain": {"@id": "ex:Person"}, "rdfs:range": {"@id": "ex:Organization"}, "rdfs:comment": "A person's employer." }, { "@id": "ex:locatedIn", "@type": "owl:ObjectProperty", "rdfs:domain": {"@id": "ex:Organization"}, "rdfs:range": {"@id": "ex:Place"}, "rdfs:comment": "The city where an organization is located." } ] }
创建启用图的知识源
本演练在创建时提供本体,且不配置引入缓存。 请在创建此源之前选定本体:如果没有缓存,则不支持之后更改本体。 需要本体更新的源需要在创建时配置重新处理的缓存;不能稍后添加该缓存,也不能删除附加的本体。
对于 REST 示例,请在 REST 客户端中设置以下变量。 将占位符替换为自己的资源名称和访问令牌。 要获取访问令牌,请参阅连接到 Foundry IQ。
@search-endpoint = https://<search-service>.search.windows.net @api-version = 2026-11-01-preview @access-token = <search-access-token> @knowledge-source-name = employees-ks @knowledge-base-name = employees-kb @container-name = <blob-container> @storage-resource-id = /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account> @model-endpoint = https://<model-resource>.openai.azure.com @chat-deployment = <chat-completion-deployment> @embedding-deployment = <embedding-deployment>使用 Python、C# 或 REST 创建新的知识源。
该
graphExtraction.ontology属性是 JSON 对象,而不是 XML。 将kind设置为inline,并将value设置为序列化为 JSON 字符串的受约束 JSON-LD 文档。name属性是可选的。 对于 SDK 示例,请将上一部分中的本体保存为ontology.json,并设置以下环境变量:SEARCH_ENDPOINT、、KNOWLEDGE_SOURCE_NAME、CONTAINER_NAME、STORAGE_RESOURCE_IDMODEL_ENDPOINT、CHAT_DEPLOYMENT和EMBEDDING_DEPLOYMENT。
import json
import os
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
AzureBlobKnowledgeSource,
AzureBlobKnowledgeSourceParameters,
AzureOpenAIVectorizerParameters,
KnowledgeBaseAzureOpenAIModel,
KnowledgeSourceContentExtractionMode,
KnowledgeSourceGraphExtractionParameters,
KnowledgeSourceGraphOntology,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeSourceAzureOpenAIVectorizer,
KnowledgeSourceIngestionParameters,
)
with open("ontology.json", encoding="utf-8") as ontology_file:
entity_ontology_value = json.dumps(
json.load(ontology_file), separators=(",", ":")
)
entity_model_endpoint = os.environ["MODEL_ENDPOINT"]
entity_ingestion_parameters = KnowledgeSourceIngestionParameters(
content_extraction_mode=KnowledgeSourceContentExtractionMode.MINIMAL,
disable_image_verbalization=True,
chat_completion_model=KnowledgeBaseAzureOpenAIModel(
azure_open_ai_parameters=AzureOpenAIVectorizerParameters(
resource_url=entity_model_endpoint,
deployment_name=os.environ["CHAT_DEPLOYMENT"],
model_name="gpt-5.6-luna",
)
),
embedding_model=KnowledgeSourceAzureOpenAIVectorizer(
azure_open_ai_parameters=AzureOpenAIVectorizerParameters(
resource_url=entity_model_endpoint,
deployment_name=os.environ["EMBEDDING_DEPLOYMENT"],
model_name="text-embedding-3-small",
)
),
)
entity_graph_parameters = KnowledgeSourceGraphExtractionParameters(
graph_name="employees",
page_degree_of_parallelism=2,
ontology=KnowledgeSourceGraphOntology(
kind="inline",
name="employees-v1",
value=entity_ontology_value,
),
)
entity_blob_parameters = AzureBlobKnowledgeSourceParameters(
connection_string=f"ResourceId={os.environ['STORAGE_RESOURCE_ID']}",
container_name=os.environ["CONTAINER_NAME"],
ingestion_parameters=entity_ingestion_parameters,
graph_extraction=entity_graph_parameters,
)
entity_knowledge_source = AzureBlobKnowledgeSource(
name=os.environ["KNOWLEDGE_SOURCE_NAME"],
description="Employees, their employers, and employer locations.",
results_processing="none",
azure_blob_parameters=entity_blob_parameters,
)
entity_index_client = SearchIndexClient(
endpoint=os.environ["SEARCH_ENDPOINT"],
credential=DefaultAzureCredential(),
)
entity_index_client.create_or_update_knowledge_source(
entity_knowledge_source
)
参考:Python客户端库。
using System;
using System.IO;
using System.Text.Json;
using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;
using JsonDocument entityOntologyDocument = JsonDocument.Parse(
File.ReadAllText("ontology.json"));
string entityOntologyValue = JsonSerializer.Serialize(
entityOntologyDocument.RootElement);
var entityChatParameters = new AzureOpenAIVectorizerParameters
{
ResourceUri = new Uri(
Environment.GetEnvironmentVariable("MODEL_ENDPOINT")!),
DeploymentName =
Environment.GetEnvironmentVariable("CHAT_DEPLOYMENT")!,
ModelName = "gpt-5.6-luna"
};
var entityEmbeddingParameters = new AzureOpenAIVectorizerParameters
{
ResourceUri = new Uri(
Environment.GetEnvironmentVariable("MODEL_ENDPOINT")!),
DeploymentName =
Environment.GetEnvironmentVariable("EMBEDDING_DEPLOYMENT")!,
ModelName = "text-embedding-3-small"
};
var entityIngestionParameters = new KnowledgeSourceIngestionParameters
{
ContentExtractionMode = KnowledgeSourceContentExtractionMode.Minimal,
DisableImageVerbalization = true,
ChatCompletionModel = new KnowledgeBaseAzureOpenAIModel(
entityChatParameters),
EmbeddingModel = new KnowledgeSourceAzureOpenAIVectorizer
{
AzureOpenAIParameters = entityEmbeddingParameters
}
};
var entityGraphParameters = new KnowledgeSourceGraphExtractionParameters(
"employees")
{
PageDegreeOfParallelism = 2,
Ontology = new KnowledgeSourceGraphOntology(
KnowledgeSourceGraphOntologySourceKind.Inline,
entityOntologyValue)
{
Name = "employees-v1"
}
};
var entityBlobParameters = new AzureBlobKnowledgeSourceParameters(
connectionString:
$"ResourceId={Environment.GetEnvironmentVariable(
"STORAGE_RESOURCE_ID")}",
containerName:
Environment.GetEnvironmentVariable("CONTAINER_NAME")!)
{
IngestionParameters = entityIngestionParameters,
GraphExtraction = entityGraphParameters
};
var entityKnowledgeSource = new AzureBlobKnowledgeSource(
Environment.GetEnvironmentVariable("KNOWLEDGE_SOURCE_NAME")!,
entityBlobParameters)
{
Description = "Employees, their employers, and employer locations.",
ResultsProcessing = KnowledgeSourceResultsProcessing.None
};
var entityIndexClient = new SearchIndexClient(
new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!),
new DefaultAzureCredential());
await entityIndexClient.CreateOrUpdateKnowledgeSourceAsync(
entityKnowledgeSource);
参考:.NET客户端库。
以下请求将上一部分中的本体编码为 value 字符串。
PUT {{search-endpoint}}/knowledgesources('{{knowledge-source-name}}')?api-version={{api-version}}
Authorization: Bearer {{access-token}}
Content-Type: application/json
{
"name": "{{knowledge-source-name}}",
"kind": "azureBlob",
"description": "Employees, their employers, and employer locations.",
"resultsProcessing": "none",
"azureBlobParameters": {
"connectionString": "ResourceId={{storage-resource-id}}",
"containerName": "{{container-name}}",
"ingestionParameters": {
"contentExtractionMode": "minimal",
"disableImageVerbalization": true,
"chatCompletionModel": {
"kind": "azureOpenAI",
"azureOpenAIParameters": {
"resourceUri": "{{model-endpoint}}",
"deploymentId": "{{chat-deployment}}",
"modelName": "gpt-5.6-luna"
}
},
"embeddingModel": {
"kind": "azureOpenAI",
"azureOpenAIParameters": {
"resourceUri": "{{model-endpoint}}",
"deploymentId": "{{embedding-deployment}}",
"modelName": "text-embedding-3-small"
}
}
},
"graphExtraction": {
"graphName": "employees",
"pageDegreeOfParallelism": 2,
"ontology": {
"kind": "inline",
"name": "employees-v1",
"value": "{\"@context\":{\"owl\":\"http://www.w3.org/2002/07/owl#\",\"rdfs\":\"http://www.w3.org/2000/01/rdf-schema#\",\"ex\":\"https://schema.search.azure.com/entities#\"},\"@graph\":[{\"@id\":\"ex:Person\",\"@type\":\"owl:Class\",\"rdfs:comment\":\"A person.\"},{\"@id\":\"ex:Organization\",\"@type\":\"owl:Class\",\"rdfs:comment\":\"An organization.\"},{\"@id\":\"ex:Place\",\"@type\":\"owl:Class\",\"rdfs:comment\":\"A geographic place.\"},{\"@id\":\"ex:worksFor\",\"@type\":\"owl:ObjectProperty\",\"rdfs:domain\":{\"@id\":\"ex:Person\"},\"rdfs:range\":{\"@id\":\"ex:Organization\"},\"rdfs:comment\":\"A person's employer.\"},{\"@id\":\"ex:locatedIn\",\"@type\":\"owl:ObjectProperty\",\"rdfs:domain\":{\"@id\":\"ex:Organization\"},\"rdfs:range\":{\"@id\":\"ex:Place\"},\"rdfs:comment\":\"The city where an organization is located.\"}]}"
}
}
}
}
参考: 知识源 REST API。
预配完成后,请回读该源以获取生成的资源名称。
GET {{search-endpoint}}/knowledgesources('{{knowledge-source-name}}')?api-version={{api-version}}
Authorization: Bearer {{access-token}}
参考: 知识源 REST API。
等待 azureBlobParameters.createdResources.graphIndex 出现;创建响应中可能不存在它。 将返回的名称用于直接图查询,并将 createdResources.index 用于源区块查找。 这些属性是只读的。 该源拥有其生成的数据源、索引器、技能组、区块索引和图索引。
验证提取是否完成
创建开始引入。 关系在处理源内容时显示在关系图中。
获取源状态。
GET {{search-endpoint}}/knowledgesources('{{knowledge-source-name}}')/status?api-version={{api-version}} Authorization: Bearer {{access-token}}参考: 知识源 REST API。
请等待同步完成。
lastSynchronizationState.endTime检查是否存在、currentSynchronizationState是否为空且lastSynchronizationState.itemsUpdatesFailed为零。 如果引入失败,请检查同步错误和所生成索引器的状态。synchronizationStatus: "active"表示源可用于同步,而不是提取已完成。 返回时,graphStatistics.triplesWritten描述该同步期间的写入,而不是图的总大小。
通过知识库查询图
知识库将自然语言关系问题转换为 GQL。 其模型配置与用于提取图的模型分开。
使用 Python、C# 或 REST 创建一个引用启用了图的源的知识库。 如果适用,请重复使用现有模型部署,但在知识库上显式对其进行配置。
对于 SDK 示例,还可以在进程环境中设置
KNOWLEDGE_BASE_NAME。
import os
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
AzureOpenAIVectorizerParameters,
KnowledgeBase,
KnowledgeBaseAzureOpenAIModel,
KnowledgeSourceReference,
)
from azure.search.documents.knowledgebases.models import (
KnowledgeRetrievalLowReasoningEffort,
KnowledgeRetrievalOutputMode,
)
entity_kb_model_parameters = AzureOpenAIVectorizerParameters(
resource_url=os.environ["MODEL_ENDPOINT"],
deployment_name=os.environ["CHAT_DEPLOYMENT"],
model_name="gpt-5.6-luna",
)
entity_knowledge_base = KnowledgeBase(
name=os.environ["KNOWLEDGE_BASE_NAME"],
knowledge_sources=[
KnowledgeSourceReference(
name=os.environ["KNOWLEDGE_SOURCE_NAME"]
)
],
models=[
KnowledgeBaseAzureOpenAIModel(
azure_open_ai_parameters=entity_kb_model_parameters
)
],
retrieval_reasoning_effort=KnowledgeRetrievalLowReasoningEffort(),
output_mode=KnowledgeRetrievalOutputMode.EXTRACTIVE_DATA,
retrieval_instructions=(
"Use graph_search for entity relationship questions. "
"Answer the relationship question by traversing the graph, "
"rather than using ordinary text search."
),
)
entity_kb_index_client = SearchIndexClient(
endpoint=os.environ["SEARCH_ENDPOINT"],
credential=DefaultAzureCredential(),
)
entity_kb_index_client.create_or_update_knowledge_base(
entity_knowledge_base
)
参考:Python客户端库。
using System;
using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;
var entityKnowledgeBaseModelParameters =
new AzureOpenAIVectorizerParameters
{
ResourceUri = new Uri(
Environment.GetEnvironmentVariable("MODEL_ENDPOINT")!),
DeploymentName =
Environment.GetEnvironmentVariable("CHAT_DEPLOYMENT")!,
ModelName = "gpt-5.6-luna"
};
var entityKnowledgeBase = new KnowledgeBase(
Environment.GetEnvironmentVariable("KNOWLEDGE_BASE_NAME")!,
[
new KnowledgeSourceReference(
Environment.GetEnvironmentVariable(
"KNOWLEDGE_SOURCE_NAME")!)
])
{
RetrievalReasoningEffort =
new KnowledgeRetrievalLowReasoningEffort(),
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
RetrievalInstructions =
"Use graph_search for entity relationship questions. " +
"Answer the relationship question by traversing the graph, " +
"rather than using ordinary text search."
};
entityKnowledgeBase.Models.Add(
new KnowledgeBaseAzureOpenAIModel(
entityKnowledgeBaseModelParameters));
var entityKnowledgeBaseIndexClient = new SearchIndexClient(
new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!),
new DefaultAzureCredential());
await entityKnowledgeBaseIndexClient.CreateOrUpdateKnowledgeBaseAsync(
entityKnowledgeBase);
参考:.NET客户端库。
PUT {{search-endpoint}}/knowledgebases('{{knowledge-base-name}}')?api-version={{api-version}}
Authorization: Bearer {{access-token}}
Content-Type: application/json
{
"name": "{{knowledge-base-name}}",
"knowledgeSources": [{"name": "{{knowledge-source-name}}"}],
"models": [
{
"kind": "azureOpenAI",
"azureOpenAIParameters": {
"resourceUri": "{{model-endpoint}}",
"deploymentId": "{{chat-deployment}}",
"modelName": "gpt-5.6-luna"
}
}
],
"retrievalReasoningEffort": {"kind": "low"},
"outputMode": "extractiveData",
"retrievalInstructions": "Use graph_search for entity relationship questions. Answer the relationship question by traversing the graph, rather than using ordinary text search."
}
参考: 创建知识库。
使用 Python、C# 或 REST 运行以下查询。
请求启用活动和源引用。 它还会选择启用生成式查询披露和源文档水化。
import os
from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
AgentRuntimeGraphHydrateDocumentsParams,
AgentRuntimeGraphParams,
AgentRuntimeGraphProvenanceParams,
AzureBlobKnowledgeSourceParams,
KnowledgeBaseMessage,
KnowledgeBaseMessageTextContent,
KnowledgeBaseRetrievalRequest,
)
source = AzureBlobKnowledgeSourceParams(
knowledge_source_name=os.environ["KNOWLEDGE_SOURCE_NAME"],
include_references=True,
include_reference_source_data=True,
fail_on_error=True,
graph_parameters=AgentRuntimeGraphParams(
include_query=True,
provenance=AgentRuntimeGraphProvenanceParams(
kind="hydrate",
hydrate_documents=AgentRuntimeGraphHydrateDocumentsParams(
select="uid,snippet,snippet_parent_id,blob_url", top=10
),
),
),
)
request = KnowledgeBaseRetrievalRequest(
messages=[
KnowledgeBaseMessage(
role="user",
content=[
KnowledgeBaseMessageTextContent(
text=(
"Which people work for organizations located in Seattle? "
"Return their names, organization names, and city names."
)
)
],
)
],
include_activity=True,
output_mode="extractiveData",
max_runtime_in_seconds=60,
knowledge_source_params=[source],
)
with KnowledgeBaseRetrievalClient(
endpoint=os.environ["SEARCH_ENDPOINT"],
credential=DefaultAzureCredential(),
knowledge_base_name=os.environ["KNOWLEDGE_BASE_NAME"],
) as client:
result = client.retrieve(request)
参考:Python客户端库。
using System;
using Azure;
using Azure.Identity;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
var source = new AzureBlobKnowledgeSourceParams(
Environment.GetEnvironmentVariable("KNOWLEDGE_SOURCE_NAME")!)
{
IncludeReferences = true,
IncludeReferenceSourceData = true,
FailOnError = true,
GraphParameters = new AgentRuntimeGraphParams
{
IncludeQuery = true,
Provenance = new AgentRuntimeGraphProvenanceParams
{
Kind = KnowledgeSourceGraphProvenanceKind.Hydrate,
HydrateDocuments = new AgentRuntimeGraphHydrateDocumentsParams
{
Select = "uid,snippet,snippet_parent_id,blob_url",
Top = 10
}
}
}
};
var request = new KnowledgeBaseRetrievalRequest
{
IncludeActivity = true,
OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
MaxRuntimeInSeconds = 60
};
request.Messages.Add(new KnowledgeBaseMessage(
[new KnowledgeBaseMessageTextContent(
"Which people work for organizations located in Seattle? " +
"Return their names, organization names, and city names.")])
{
Role = "user"
});
request.KnowledgeSourceParams.Add(source);
var client = new KnowledgeBaseRetrievalClient(
new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!),
Environment.GetEnvironmentVariable("KNOWLEDGE_BASE_NAME")!,
new DefaultAzureCredential());
Response<KnowledgeBaseRetrievalResponse> result =
await client.RetrieveAsync(request);
参考:.NET客户端库。
POST {{search-endpoint}}/knowledgebases('{{knowledge-base-name}}')/retrieve?api-version={{api-version}}
Authorization: Bearer {{access-token}}
Content-Type: application/json
{
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Which people work for organizations located in Seattle? Return their names, organization names, and city names."
}
]
}
],
"includeActivity": true,
"outputMode": "extractiveData",
"maxRuntimeInSeconds": 60,
"knowledgeSourceParams": [
{
"kind": "azureBlob",
"knowledgeSourceName": "{{knowledge-source-name}}",
"includeReferences": true,
"includeReferenceSourceData": true,
"failOnError": true,
"graphParameters": {
"includeQuery": true,
"provenance": {
"kind": "hydrate",
"hydrateDocuments": {
"select": "uid,snippet,snippet_parent_id,blob_url",
"top": 10
}
}
}
}
]
}
参考: 知识检索 REST API。
图引用标识 graphIndexName 中的托管图和 activitySource 中执行的活动。 启用水化后,额外的参考内容会在 sourceData 中包含支持性的源区块。 它们的 uid、snippet_parent_id 和 blob_url 可让你将结果追溯到其区块和父文档。
知识库图来源默认为 none. 要返回不带水化区块的图行,请省略 graphParameters.provenance。 hydration top 功能可独立于图形行数限制源文档。
使用 GQL 直接查询图
当应用程序提供遍历本身时,请使用托管图形索引。 直接 search.graph 操作需要 gql。 其可选 search 属性仅适用于全文搜索。
在 REST 客户端中设置
GRAPH_INDEX_NAME,或在 SDK 进程环境中设置graph-index-name,将其设为返回的createdResources.graphIndex值。运行一个从一个人到雇主再到一个城市的两跳遍历。 标签和谓词与前面定义的本体匹配。
import os
from azure.identity import DefaultAzureCredential
from azure.search.documents import SearchClient
from azure.search.documents.models import (
GraphQueryProvenanceHydrateDocumentsParameters,
GraphQueryProvenanceParameters,
)
gql = (
"MATCH (person:Person)-[job]->(org:Organization)"
"-[location]->(city:Place) "
"WHERE job.predicate = 'worksFor' "
"AND location.predicate = 'locatedIn' "
"AND city.name = 'Seattle' "
"RETURN person.name AS person, org.name AS organization, "
"city.name AS city LIMIT 10"
)
with SearchClient(
os.environ["SEARCH_ENDPOINT"],
os.environ["GRAPH_INDEX_NAME"],
DefaultAzureCredential(),
) as client:
result = client.graph(
gql=gql,
include_statistics=True,
include_diagnostics=True,
provenance=GraphQueryProvenanceParameters(
kind="hydrate",
max_evidence_per_row=10,
hydrate_documents=GraphQueryProvenanceHydrateDocumentsParameters(
select="uid,snippet,snippet_parent_id,blob_url"
),
),
)
参考:Python客户端库。
using System;
using Azure;
using Azure.Identity;
using Azure.Search.Documents;
using Azure.Search.Documents.Models;
string gql =
"MATCH (person:Person)-[job]->(org:Organization)" +
"-[location]->(city:Place) " +
"WHERE job.predicate = 'worksFor' " +
"AND location.predicate = 'locatedIn' " +
"AND city.name = 'Seattle' " +
"RETURN person.name AS person, org.name AS organization, " +
"city.name AS city LIMIT 10";
var graphClient = new SearchClient(
new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!),
Environment.GetEnvironmentVariable("GRAPH_INDEX_NAME")!,
new DefaultAzureCredential());
Response<GraphQueryResult> graphResult = await graphClient.GraphAsync(
gql: gql,
includeStatistics: true,
includeDiagnostics: true,
provenance: new GraphQueryProvenanceParameters(
GraphQueryProvenanceKind.Hydrate)
{
MaxEvidencePerRow = 10,
HydrateDocuments =
new GraphQueryProvenanceHydrateDocumentsParameters
{
Select = "uid,snippet,snippet_parent_id,blob_url"
}
});
参考:.NET客户端库。
POST {{search-endpoint}}/indexes('{{graph-index-name}}')/docs/search.graph?api-version={{api-version}}
Authorization: Bearer {{access-token}}
Content-Type: application/json
{
"gql": "MATCH (person:Person)-[job]->(org:Organization)-[location]->(city:Place) WHERE job.predicate = 'worksFor' AND location.predicate = 'locatedIn' AND city.name = 'Seattle' RETURN person.name AS person, org.name AS organization, city.name AS city LIMIT 10",
"includeStatistics": true,
"includeDiagnostics": true,
"provenance": {
"kind": "hydrate",
"maxEvidencePerRow": 10,
"hydrateDocuments": {
"select": "uid,snippet,snippet_parent_id,blob_url"
}
}
}
参考: 文档 REST API。
每行的 @search.graphProvenance 都包含支持性的 edgeId、chunkId 和 parentId 标识符。 将 edgeId 连接到图断言的 id,并在生成的区块索引中将 chunkId 连接到 uid。 水合区块在 @search.graphProvenanceDocuments 中跨行共享;对于此托管图,映射键是区块 ID。
使用 evidenceCount.relation 来解释证据计数:exact 表示计数是完整的,并且 lowerBound 意味着收集是受限的,因此可以存在更多的支持证据。
maxEvidencePerRow 限制收集多少证据。
对于没有文档水合的标识符,请使用 kind: "ids" 并省略 hydrateDocuments。 直接水化支持字段选择,但与知识库水化不同,它不接受 top。
图形查询疑难解答
对于检索失败,请检查顶层错误;如果返回了 graphSearch 活动,也请一并检查。
| 问题 | Action |
|---|---|
| 查询模型限制 | 当知识库的查询模型返回 429(TooManyRequests)时,检索请求可以返回 502 和 All retrieval tasks failed。 检查该模型部署的 令牌和请求速率限制 ,并遵循 速率限制重试指南 ,而不是持续重新发送请求。 此查询模型失败并不表明存在提取失败,也不表示无服务器图形查询受到限制。 |
| 没有预期的图行 | 验证 同步是否已完成,然后运行 直接 GQL 遍历 以检查存储的关系。 空查询结果并不能证明提取已成功。 |
清理测试资源
删除为此练习创建的知识库,然后删除知识源。
删除源会删除其生成的搜索资源,包括托管图形索引,但不会删除你的 Blob 数据。 仅移除测试 Blob,或者,如果该容器是为本练习创建的,则移除该容器。 保留共享存储帐户和模型部署。
相关内容
有关基础引入设置和检索工作流,请参阅:
- 创建 Blob 知识源。
- 创建知识库。
- 检索知识。