

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Esecuzione di query su entità di lineage
<a name="querying-lineage-entities"></a>

Amazon SageMaker AI genera automaticamente grafici di entità di derivazione man mano che li utilizzi. Puoi eseguire query su questi dati per rispondere a una serie di domande. Di seguito vengono fornite istruzioni su come eseguire query su questi dati in SDK per Python. 

Per informazioni su come visualizzare una linea di modelli registrati in Amazon SageMaker Studio, consulta[Visualizzazione dei dettagli del lineage del modello in Studio](model-registry-lineage-view-studio.md).

Puoi eseguire query sulle tue entità di lineage per:
+ Recuperare tutti i set di dati utilizzati per la creazione di un modello.
+ Recuperare tutti i processi utilizzati per la creazione di un endpoint.
+ Recuperare tutti i modelli che utilizzano un set di dati.
+ Recuperare tutti gli endpoint che utilizzano un modello.
+ Recuperare quali endpoint derivano da un determinato set di dati.
+ Recuperare l'esecuzione della pipeline che ha creato un processo di addestramento.
+ Recuperare le relazioni tra le entità per investigazione, governance e riproducibilità.
+ Recuperare tutte le prove downstream che utilizzano l'artefatto.
+ Recuperare tutte le prove upstream che utilizzano l'artefatto.
+ Recuperare un elenco di artefatti che utilizzano l'uri S3 fornito.
+ Recuperare gli artefatti upstream che utilizzano l'artefatto del set di dati.
+ Recuperare gli artefatti downstream che utilizzano l'artefatto del set di dati.
+ Recuperare i set di dati che utilizzano l'artefatto dell'immagine.
+ Recuperare le operazioni che utilizzano il contesto.
+ Recuperare i processi di elaborazione che utilizzano l'endpoint.
+ Recuperare i processi di trasformazione che utilizzano l'endpoint.
+ Recuperare i componenti di prova che utilizzano l'endpoint.
+ Recuperare l'ARN per l'esecuzione della pipeline associata al gruppo di pacchetti di modelli.
+ Recuperare tutti gli artefatti che utilizzano l'operazione.
+ Recuperare tutti i set di dati upstream che utilizzano l'operazione di approvazione del pacchetto del modello.
+ Recuperare il pacchetto del modello dall'operazione di approvazione del pacchetto del modello.
+ Recuperare i contesti degli endpoint downstream che utilizzano l'endpoint.
+ Recuperare l'ARN per l'esecuzione della pipeline associata al componente di prova.
+ Recuperare i set di dati che utilizzano il componente di prova.
+ Recuperare i modelli che utilizzano il componente di prova.
+ Esplora il tuo lineage per visualizzarlo.

**Limitazioni**
+ L'esecuzione di query sul lineage non è disponibile nelle seguenti Regioni:
  + Africa (Città del Capo) – af-south
  + Asia Pacifico (Giacarta) – ap-southeast-3
  + Asia Pacifico (Osaka) - ap-northeast-3
  + Europa (Milano) – eu-south-1
  + Europa (Spagna): eu-south-2
  + Israele (Tel Aviv) il-central-1
+ La profondità massima di relazioni da rilevare è attualmente limitata a 10.
+ Il filtraggio è limitato alle seguenti proprietà: data ultima modifica, data di creazione, tipo e tipo di entità di lineage. 

**Topics**
+ [Nozioni di base sull'esecuzione di query sulle entità di lineage](#querying-lineage-entities-getting-started)

## Nozioni di base sull'esecuzione di query sulle entità di lineage
<a name="querying-lineage-entities-getting-started"></a>

Il modo più semplice per iniziare è tramite:
+ [Amazon SageMaker AI SDK per Python](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/lineage/artifact.py#L397) che ha definito molti casi d'uso comuni.
+ [Per un notebook che dimostra come utilizzare SageMaker AI Lineage per interrogare le relazioni attraverso il grafico APIs di derivazione, consulta .ipynb. sagemaker-lineage-multihop-queries](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/sagemaker-lineage-multihop-queries.ipynb)

Gli esempi seguenti mostrano come utilizzare `LineageQuery` e costruire query per rispondere `LineageFilter` APIs a domande sul Lineage Graph ed estrarre le relazioni tra entità per alcuni casi d'uso.

**Example Utilizzo dell'API `LineageQuery` per trovare associazioni di entità**  

```
from sagemaker.lineage.context import Context, EndpointContext
from sagemaker.lineage.action import Action
from sagemaker.lineage.association import Association
from sagemaker.lineage.artifact import Artifact, ModelArtifact, DatasetArtifact

from sagemaker.lineage.query import (
    LineageQuery,
    LineageFilter,
    LineageSourceEnum,
    LineageEntityEnum,
    LineageQueryDirectionEnum,
)
# Find the endpoint context and model artifact that should be used for the lineage queries.

contexts = Context.list(source_uri=endpoint_arn)
context_name = list(contexts)[0].context_name
endpoint_context = EndpointContext.load(context_name=context_name)
```

**Example Trova tutti i set di dati associati a un endpoint**  

```
# Define the LineageFilter to look for entities of type `ARTIFACT` and the source of type `DATASET`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT], sources=[LineageSourceEnum.DATASET]
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the lineage objects corresponding to the datasets
dataset_artifacts = []
for vertex in query_result.vertices:
    dataset_artifacts.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(dataset_artifacts)
```

**Example Trova i modelli associati a un endpoint**  

```
# Define the LineageFilter to look for entities of type `ARTIFACT` and the source of type `MODEL`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT], sources=[LineageSourceEnum.MODEL]
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the lineage objects corresponding to the model
model_artifacts = []
for vertex in query_result.vertices:
    model_artifacts.append(vertex.to_lineage_object().source.source_uri)

# The results of the `LineageQuery` API call return the ARN of the model deployed to the endpoint along with
# the S3 URI to the model.tar.gz file associated with the model
pp.pprint(model_artifacts)
```

**Example Trova i componenti di prova associati all'endpoint**  

```
# Define the LineageFilter to look for entities of type `TRIAL_COMPONENT` and the source of type `TRAINING_JOB`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.TRIAL_COMPONENT],
    sources=[LineageSourceEnum.TRAINING_JOB],
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the ARNs of the training jobs associated with this Endpoint
trial_components = []
for vertex in query_result.vertices:
    trial_components.append(vertex.arn)

pp.pprint(trial_components)
```

**Example Modifica del punto focale del lineage**  
`LineageQuery` può essere modificato in modo che abbia un diverso `start_arns`, il che cambia il punto focale del lineage. Inoltre, `LineageFilter` può utilizzare origini ed entità molteplici per espandere l'ambito della query.  
Di seguito utilizziamo il modello come punto focale del lineage e troviamo gli endpoint e i set di dati ad esso associati.  

```
# Get the ModelArtifact

model_artifact_summary = list(Artifact.list(source_uri=model_package_arn))[0]
model_artifact = ModelArtifact.load(artifact_arn=model_artifact_summary.artifact_arn)
query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[LineageSourceEnum.ENDPOINT, LineageSourceEnum.DATASET],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # Find all the entities that descend from the model, i.e. the endpoint
    direction=LineageQueryDirectionEnum.DESCENDANTS,
    include_edges=False,
)

associations = []
for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # Find all the entities that ascend from the model, i.e. the datasets
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(associations)
```

**Example Utilizzo di `LineageQueryDirectionEnum.BOTH` per trovare relazioni di ascendenza e discendenza**  
Quando la direzione è impostata su `BOTH`, la query attraversa il grafico per trovare le relazioni di ascendenza e discendenza. Questo attraversamento avviene non solo dal nodo iniziale, ma da ogni nodo visitato. Ad esempio, se un processo di addestramento viene eseguito due volte ed entrambi i modelli generati dal processo di addestramento vengono implementati sugli endpoint, il risultato della query con direzione impostata su `BOTH` mostra entrambi gli endpoint. Questo perché la stessa immagine viene utilizzata per il addestramento e l'implementazione del modello. Poiché l'immagine è comune al modello, nel risultato della query vengono visualizzati `start_arn` ed entrambi gli endpoint.  

```
query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[LineageSourceEnum.ENDPOINT, LineageSourceEnum.DATASET],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # This specifies that the query should look for associations both ascending and descending for the start
    direction=LineageQueryDirectionEnum.BOTH,
    include_edges=False,
)

associations = []
for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(associations)
```

**Example Direzioni in `LineageQuery`: `ASCENDANTS` e `DESCENDANTS`**  
Per capire la direzione del grafico di lineage, prendi il seguente grafico delle relazioni tra entità: Set di dati -> Processo di addestramento -> Modello -> Endpoint  
L'endpoint è una discendenza del modello e il modello è una discendenza del set di dati. Analogamente, il modello è un'ascendenza dell'endpoint. Il parametro `direction` può essere utilizzato per specificare se la query deve restituire entità che rappresentano discendenze o ascendenze dell'entità in `start_arns`. Se `start_arns` contiene un modello e la direzione è `DESCENDANTS`, la query restituisce l'endpoint. Se la direzione è `ASCENDANTS`, la query restituisce il set di dati.  

```
# In this example, we'll look at the impact of specifying the direction as ASCENDANT or DESCENDANT in a `LineageQuery`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[
        LineageSourceEnum.ENDPOINT,
        LineageSourceEnum.MODEL,
        LineageSourceEnum.DATASET,
        LineageSourceEnum.TRAINING_JOB,
    ],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

ascendant_artifacts = []

# The lineage entity returned for the Training Job is a TrialComponent which can't be converted to a
# lineage object using the method `to_lineage_object()` so we extract the TrialComponent ARN.
for vertex in query_result.vertices:
    try:
        ascendant_artifacts.append(vertex.to_lineage_object().source.source_uri)
    except:
        ascendant_artifacts.append(vertex.arn)

print("Ascendant artifacts : ")
pp.pprint(ascendant_artifacts)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.DESCENDANTS,
    include_edges=False,
)

descendant_artifacts = []
for vertex in query_result.vertices:
    try:
        descendant_artifacts.append(vertex.to_lineage_object().source.source_uri)
    except:
        # Handling TrialComponents.
        descendant_artifacts.append(vertex.arn)

print("Descendant artifacts : ")
pp.pprint(descendant_artifacts)
```

**Example Funzioni di supporto SDK per semplificare l'esecuzione di query sul lineage**  
Le classi `EndpointContext`, `ModelArtifact` e `DatasetArtifact` dispongono di funzioni di supporto che fungono da wrapper sull'API `LineageQuery` per semplificare l'utilizzo di determinate query di lineage. Il seguente esempio illustra come utilizzare queste funzioni di supporto.  

```
# Find all the datasets associated with this endpoint

datasets = []
dataset_artifacts = endpoint_context.dataset_artifacts()
for dataset in dataset_artifacts:
    datasets.append(dataset.source.source_uri)
print("Datasets : ", datasets)

# Find the training jobs associated with the endpoint
training_job_artifacts = endpoint_context.training_job_arns()
training_jobs = []
for training_job in training_job_artifacts:
    training_jobs.append(training_job)
print("Training Jobs : ", training_jobs)

# Get the ARN for the pipeline execution associated with this endpoint (if any)
pipeline_executions = endpoint_context.pipeline_execution_arn()
if pipeline_executions:
    for pipeline in pipelines_executions:
        print(pipeline)

# Here we use the `ModelArtifact` class to find all the datasets and endpoints associated with the model

dataset_artifacts = model_artifact.dataset_artifacts()
endpoint_contexts = model_artifact.endpoint_contexts()

datasets = [dataset.source.source_uri for dataset in dataset_artifacts]
endpoints = [endpoint.source.source_uri for endpoint in endpoint_contexts]

print("Datasets associated with this model : ")
pp.pprint(datasets)

print("Endpoints associated with this model : ")
pp.pprint(endpoints)

# Here we use the `DatasetArtifact` class to find all the endpoints hosting models that were trained with a particular dataset
# Find the artifact associated with the dataset

dataset_artifact_arn = list(Artifact.list(source_uri=training_data))[0].artifact_arn
dataset_artifact = DatasetArtifact.load(artifact_arn=dataset_artifact_arn)

# Find the endpoints that used this training dataset
endpoint_contexts = dataset_artifact.endpoint_contexts()
endpoints = [endpoint.source.source_uri for endpoint in endpoint_contexts]

print("Endpoints associated with the training dataset {}".format(training_data))
pp.pprint(endpoints)
```

**Example Ottenere una visualizzazione del grafico di lineage**  
Una classe di supporto `Visualizer` viene fornita nel notebook di esempio [visualizer.py](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/visualizer.py) per aiutare a tracciare il grafico di lineage. Quando viene renderizzata la risposta alla query, viene visualizzato un grafico con le relazioni di lineage da `StartArns`. Da `StartArns` la visualizzazione mostra le relazioni con le altre entità di lineage restituite nell'operazione API `query_lineage`.  

```
# Graph APIs
# Here we use the boto3 `query_lineage` API to generate the query response to plot.

from visualizer import Visualizer

query_response = sm_client.query_lineage(
    StartArns=[endpoint_context.context_arn], Direction="Ascendants", IncludeEdges=True
)

viz = Visualizer()
viz.render(query_response, "Endpoint")
        
        query_response = sm_client.query_lineage(
    StartArns=[model_artifact.artifact_arn], Direction="Ascendants", IncludeEdges=True
)
viz.render(query_response, "Model")
```