Administra y encuentra funciones

Aprende a administrar y encontrar atributos.

Crea un atributo

Crea un atributo único para un tipo de entidad existente. Para crear varios atributos en una sola solicitud, consulta Crea atributos por lotes.

IU web

  1. En la sección de Vertex AI de la consola de Google Cloud, ve a la página Funciones.

    Ve a la página Atributos

  2. Selecciona una región de la lista desplegable Región.
  3. En la tabla de atributos, consulta la columna Tipo de entidad y haz clic en el tipo de entidad al que agregarás atributos.
  4. Haz clic en Agregar funciones para abrir el panel Agregar funciones.
  5. Especifica un nombre, un tipo de valor y (opcionalmente) una descripción para la función.
  6. Para habilitar la supervisión del valor de las funciones (Vista previa), en Supervisión de funciones, selecciona Anular la configuración de supervisión del tipo de entidad y, luego, ingresa lo siguiente: la cantidad de días entre instantáneas. Esta configuración anula las configuraciones de supervisión existentes o futuras en el tipo de entidad de la función. Para obtener más información, consulta Supervisión del valor de los atributos.
  7. Para agregar más atributos, haz clic en Agregar otro atributo.
  8. Haz clic en Guardar.

REST

Si deseas crear un atributo para un tipo de entidad existente, envía una solicitud POST mediante el método featurestores.entityTypes.features.create.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.
  • FEATURESTORE_ID: ID del featurestore.
  • ENTITY_TYPE_ID: ID del tipo de entidad.
  • FEATURE_ID: Es un ID para el atributo.
  • DESCRIPTION: Es la descripción del atributo.
  • VALUE_TYPE: El tipo de valor de la función.

Método HTTP y URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID?featureId=FEATURE_ID

Cuerpo JSON de la solicitud:

{
  "description": "DESCRIPTION",
  "valueType": "VALUE_TYPE"
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID?featureId=FEATURE_ID"

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID?featureId=FEATURE_ID" | Select-Object -Expand Content

Deberías ver un resultado similar al siguiente. Puedes usar el OPERATION_ID en la respuesta para obtener el estado de la operación.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateFeatureOperationMetadata",
    "genericMetadata": {
      "createTime": "2021-03-02T00:04:13.039166Z",
      "updateTime": "2021-03-02T00:04:13.039166Z"
    }
  }
}

Python

Si deseas obtener información para instalar o actualizar el SDK de Python, consulta Instala el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia de la API de Python.

from google.cloud import aiplatform

def create_feature_sample(
    project: str,
    location: str,
    feature_id: str,
    value_type: str,
    entity_type_id: str,
    featurestore_id: str,
):

    aiplatform.init(project=project, location=location)

    my_feature = aiplatform.Feature.create(
        feature_id=feature_id,
        value_type=value_type,
        entity_type_name=entity_type_id,
        featurestore_id=featurestore_id,
    )

    my_feature.wait()

    return my_feature

Python

La biblioteca cliente de Vertex AI se incluye cuando instalas el SDK de Vertex AI para Python. Si deseas obtener información sobre cómo instalar el SDK de Vertex AI para Python, consulta Instala el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de AI de Vertex para la API de Python.

from google.cloud import aiplatform

def create_feature_sample(
    project: str,
    featurestore_id: str,
    entity_type_id: str,
    feature_id: str,
    value_type: aiplatform.gapic.Feature.ValueType,
    description: str = "sample feature",
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints, which need to be
    # in the same region or multi-region overlap with the Feature Store location.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
    parent = f"projects/{project}/locations/{location}/featurestores/{featurestore_id}/entityTypes/{entity_type_id}"
    create_feature_request = aiplatform.gapic.CreateFeatureRequest(
        parent=parent,
        feature=aiplatform.gapic.Feature(
            value_type=value_type, description=description
        ),
        feature_id=feature_id,
    )
    lro_response = client.create_feature(request=create_feature_request)
    print("Long running operation:", lro_response.operation.name)
    create_feature_response = lro_response.result(timeout=timeout)
    print("create_feature_response:", create_feature_response)

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateFeatureOperationMetadata;
import com.google.cloud.aiplatform.v1.CreateFeatureRequest;
import com.google.cloud.aiplatform.v1.EntityTypeName;
import com.google.cloud.aiplatform.v1.Feature;
import com.google.cloud.aiplatform.v1.Feature.ValueType;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateFeatureSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    String featureId = "YOUR_FEATURE_ID";
    String description = "YOUR_FEATURE_DESCRIPTION";
    ValueType valueType = ValueType.STRING;
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    int timeout = 900;
    createFeatureSample(
        project,
        featurestoreId,
        entityTypeId,
        featureId,
        description,
        valueType,
        location,
        endpoint,
        timeout);
  }

  static void createFeatureSample(
      String project,
      String featurestoreId,
      String entityTypeId,
      String featureId,
      String description,
      ValueType valueType,
      String location,
      String endpoint,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {

    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      Feature feature =
          Feature.newBuilder().setDescription(description).setValueType(valueType).build();

      CreateFeatureRequest createFeatureRequest =
          CreateFeatureRequest.newBuilder()
              .setParent(
                  EntityTypeName.of(project, location, featurestoreId, entityTypeId).toString())
              .setFeature(feature)
              .setFeatureId(featureId)
              .build();

      OperationFuture<Feature, CreateFeatureOperationMetadata> featureFuture =
          featurestoreServiceClient.createFeatureAsync(createFeatureRequest);
      System.out.format("Operation name: %s%n", featureFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Feature featureResponse = featureFuture.get(timeout, TimeUnit.SECONDS);
      System.out.println("Create Feature Response");
      System.out.format("Name: %s%n", featureResponse.getName());
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const featureId = 'YOUR_FEATURE_ID';
// const valueType = 'FEATURE_VALUE_DATA_TYPE';
// const description = 'YOUR_ENTITY_TYPE_DESCRIPTION';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function createFeature() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}`;

  const feature = {
    valueType: valueType,
    description: description,
  };

  const request = {
    parent: parent,
    feature: feature,
    featureId: featureId,
  };

  // Create Feature request
  const [operation] = await featurestoreServiceClient.createFeature(request, {
    timeout: Number(timeout),
  });
  const [response] = await operation.promise();

  console.log('Create feature response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createFeature();

Crea funciones por lotes

Crea atributos de forma masiva para un tipo existente. Para las solicitudes de creación por lotes, Vertex AI Feature Store (Legacy) crea varios atributos a la vez, lo cual es más rápido para crear una gran cantidad de atributos en comparación con el método featurestores.entityTypes.features.create.

IU web

Consulta cómo crear una función.

REST

A fin de crear una o más características para un tipo de entidad existente, envía una solicitud POST con el método featurestores.entityTypes.features.batchCreate, como se muestra en el siguiente ejemplo.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.
  • FEATURESTORE_ID: ID del featurestore.
  • ENTITY_TYPE_ID: ID del tipo de entidad.
  • PARENT: Es el nombre del recurso del tipo de entidad en el que se crearán los atributos. Formato obligatorio:
    projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID
  • FEATURE_ID: Es un ID para el atributo.
  • DESCRIPTION: Es la descripción del atributo.
  • VALUE_TYPE: El tipo de valor de la función.
  • DURATION: (Opcional) La duración del intervalo entre instantáneas en segundos. El valor debe terminar con una “s”.

Método HTTP y URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features:batchCreate

Cuerpo JSON de la solicitud:

{
  "requests": [
    {
      "parent" : "PARENT_1",
      "feature": {
        "description": "DESCRIPTION_1",
        "valueType": "VALUE_TYPE_1",
        "monitoringConfig": {
          "snapshotAnalysis": {
            "monitoringInterval": "DURATION"
          }
        }
      },
      "featureId": "FEATURE_ID_1"
    },
    {
      "parent" : "PARENT_2",
      "feature": {
        "description": "DESCRIPTION_2",
        "valueType": "VALUE_TYPE_2",
        "monitoringConfig": {
          "snapshotAnalysis": {
            "monitoringInterval": "DURATION"
          }
        }
      },
      "featureId": "FEATURE_ID_2"
    }
  ]
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features:batchCreate"

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features:batchCreate" | Select-Object -Expand Content

Deberías ver un resultado similar al siguiente. Puedes usar el OPERATION_ID en la respuesta para obtener el estado de la operación.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.BatchCreateFeaturesOperationMetadata",
    "genericMetadata": {
      "createTime": "2021-03-02T00:04:13.039166Z",
      "updateTime": "2021-03-02T00:04:13.039166Z"
    }
  }
}

Python

Si deseas obtener información para instalar o actualizar el SDK de Python, consulta Instala el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia de la API de Python.

from google.cloud import aiplatform

def batch_create_features_sample(
    project: str,
    location: str,
    entity_type_id: str,
    featurestore_id: str,
    sync: bool = True,
):

    aiplatform.init(project=project, location=location)

    my_entity_type = aiplatform.featurestore.EntityType(
        entity_type_name=entity_type_id, featurestore_id=featurestore_id
    )

    FEATURE_CONFIGS = {
        "age": {"value_type": "INT64", "description": "User age"},
        "gender": {"value_type": "STRING", "description": "User gender"},
        "liked_genres": {
            "value_type": "STRING_ARRAY",
            "description": "An array of genres this user liked",
        },
    }

    my_entity_type.batch_create_features(feature_configs=FEATURE_CONFIGS, sync=sync)

Python

La biblioteca cliente de Vertex AI se incluye cuando instalas el SDK de Vertex AI para Python. Si deseas obtener información sobre cómo instalar el SDK de Vertex AI para Python, consulta Instala el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de AI de Vertex para la API de Python.

from google.cloud import aiplatform

def batch_create_features_sample(
    project: str,
    featurestore_id: str,
    entity_type_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints, which need to be
    # in the same region or multi-region overlap with the Feature Store location.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
    parent = f"projects/{project}/locations/{location}/featurestores/{featurestore_id}/entityTypes/{entity_type_id}"
    age_feature = aiplatform.gapic.Feature(
        value_type=aiplatform.gapic.Feature.ValueType.INT64, description="User age",
    )
    age_feature_request = aiplatform.gapic.CreateFeatureRequest(
        feature=age_feature, feature_id="age"
    )

    gender_feature = aiplatform.gapic.Feature(
        value_type=aiplatform.gapic.Feature.ValueType.STRING, description="User gender"
    )
    gender_feature_request = aiplatform.gapic.CreateFeatureRequest(
        feature=gender_feature, feature_id="gender"
    )

    liked_genres_feature = aiplatform.gapic.Feature(
        value_type=aiplatform.gapic.Feature.ValueType.STRING_ARRAY,
        description="An array of genres that this user liked",
    )
    liked_genres_feature_request = aiplatform.gapic.CreateFeatureRequest(
        feature=liked_genres_feature, feature_id="liked_genres"
    )

    requests = [
        age_feature_request,
        gender_feature_request,
        liked_genres_feature_request,
    ]
    batch_create_features_request = aiplatform.gapic.BatchCreateFeaturesRequest(
        parent=parent, requests=requests
    )
    lro_response = client.batch_create_features(request=batch_create_features_request)
    print("Long running operation:", lro_response.operation.name)
    batch_create_features_response = lro_response.result(timeout=timeout)
    print("batch_create_features_response:", batch_create_features_response)

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.BatchCreateFeaturesOperationMetadata;
import com.google.cloud.aiplatform.v1.BatchCreateFeaturesRequest;
import com.google.cloud.aiplatform.v1.BatchCreateFeaturesResponse;
import com.google.cloud.aiplatform.v1.CreateFeatureRequest;
import com.google.cloud.aiplatform.v1.EntityTypeName;
import com.google.cloud.aiplatform.v1.Feature;
import com.google.cloud.aiplatform.v1.Feature.ValueType;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BatchCreateFeaturesSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    int timeout = 300;
    batchCreateFeaturesSample(project, featurestoreId, entityTypeId, location, endpoint, timeout);
  }

  static void batchCreateFeaturesSample(
      String project,
      String featurestoreId,
      String entityTypeId,
      String location,
      String endpoint,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      List<CreateFeatureRequest> createFeatureRequests = new ArrayList<>();

      Feature titleFeature =
          Feature.newBuilder()
              .setDescription("The title of the movie")
              .setValueType(ValueType.STRING)
              .build();
      Feature genresFeature =
          Feature.newBuilder()
              .setDescription("The genres of the movie")
              .setValueType(ValueType.STRING)
              .build();
      Feature averageRatingFeature =
          Feature.newBuilder()
              .setDescription("The average rating for the movie, range is [1.0-5.0]")
              .setValueType(ValueType.DOUBLE)
              .build();

      createFeatureRequests.add(
          CreateFeatureRequest.newBuilder().setFeature(titleFeature).setFeatureId("title").build());

      createFeatureRequests.add(
          CreateFeatureRequest.newBuilder()
              .setFeature(genresFeature)
              .setFeatureId("genres")
              .build());

      createFeatureRequests.add(
          CreateFeatureRequest.newBuilder()
              .setFeature(averageRatingFeature)
              .setFeatureId("average_rating")
              .build());

      BatchCreateFeaturesRequest batchCreateFeaturesRequest =
          BatchCreateFeaturesRequest.newBuilder()
              .setParent(
                  EntityTypeName.of(project, location, featurestoreId, entityTypeId).toString())
              .addAllRequests(createFeatureRequests)
              .build();

      OperationFuture<BatchCreateFeaturesResponse, BatchCreateFeaturesOperationMetadata>
          batchCreateFeaturesFuture =
              featurestoreServiceClient.batchCreateFeaturesAsync(batchCreateFeaturesRequest);
      System.out.format(
          "Operation name: %s%n", batchCreateFeaturesFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      BatchCreateFeaturesResponse batchCreateFeaturesResponse =
          batchCreateFeaturesFuture.get(timeout, TimeUnit.SECONDS);
      System.out.println("Batch Create Features Response");
      System.out.println(batchCreateFeaturesResponse);
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function batchCreateFeatures() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}`;

  const ageFeature = {
    valueType: 'INT64',
    description: 'User age',
  };

  const ageFeatureRequest = {
    feature: ageFeature,
    featureId: 'age',
  };

  const genderFeature = {
    valueType: 'STRING',
    description: 'User gender',
  };

  const genderFeatureRequest = {
    feature: genderFeature,
    featureId: 'gender',
  };

  const likedGenresFeature = {
    valueType: 'STRING_ARRAY',
    description: 'An array of genres that this user liked',
  };

  const likedGenresFeatureRequest = {
    feature: likedGenresFeature,
    featureId: 'liked_genres',
  };

  const requests = [
    ageFeatureRequest,
    genderFeatureRequest,
    likedGenresFeatureRequest,
  ];

  const request = {
    parent: parent,
    requests: requests,
  };

  // Batch Create Features request
  const [operation] = await featurestoreServiceClient.batchCreateFeatures(
    request,
    {timeout: Number(timeout)}
  );
  const [response] = await operation.promise();

  console.log('Batch create features response');
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
batchCreateFeatures();

Enumerar funciones

Enumera todos los atributos en una ubicación determinada. Para buscar atributos en todos los tipos de entidades y featurestores en una ubicación determinada, consulta el método Búsqueda de atributos.

IU web

  1. En la sección de Vertex AI de la consola de Google Cloud, ve a la página Funciones.

    Ve a la página Atributos

  2. Selecciona una región de la lista desplegable Región.
  3. En la tabla de atributos, consulta la columna Funciones a fin de ver las características de tu proyecto para la región seleccionada.

REST

Para enumerar todas las funciones de un solo tipo de entidad, envía una solicitud GET mediante el método featurestores.entityTypes.features.list.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.
  • FEATURESTORE_ID: ID del featurestore.
  • ENTITY_TYPE_ID: ID del tipo de entidad.

Método HTTP y URL:

GET https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "features": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID_1",
      "description": "DESCRIPTION",
      "valueType": "VALUE_TYPE",
      "createTime": "2021-03-01T22:41:20.626644Z",
      "updateTime": "2021-03-01T22:41:20.626644Z",
      "labels": {
        "environment": "testing"
      },
      "etag": "AMEw9yP0qJeLao6P3fl9cKEGY4ie5-SanQaiN7c_Ca4QOa0u7AxwO6i75Vbp0Cr51MSf"
    },
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID_2",
      "description": "DESCRIPTION",
      "valueType": "VALUE_TYPE",
      "createTime": "2021-02-25T01:27:00.544230Z",
      "updateTime": "2021-02-25T01:27:00.544230Z",
      "labels": {
        "environment": "testing"
      },
      "etag": "AMEw9yMdrLZ7Waty0ane-DkHq4kcsIVC-piqJq7n6A_Y-BjNzPY4rNlokDHNyUqC7edw"
    },
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID_3",
      "description": "DESCRIPTION",
      "valueType": "VALUE_TYPE",
      "createTime": "2021-03-01T22:41:20.628493Z",
      "updateTime": "2021-03-01T22:41:20.628493Z",
      "labels": {
        "environment": "testing"
      },
      "etag": "AMEw9yM-sAkv-u-jzkUOToaAVovK7GKbrubd9DbmAonik-ojTWG8-hfSRYt6jHKRTQ35"
    }
  ]
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.aiplatform.v1.EntityTypeName;
import com.google.cloud.aiplatform.v1.Feature;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import com.google.cloud.aiplatform.v1.ListFeaturesRequest;
import java.io.IOException;

public class ListFeaturesSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";

    listFeaturesSample(project, featurestoreId, entityTypeId, location, endpoint);
  }

  static void listFeaturesSample(
      String project, String featurestoreId, String entityTypeId, String location, String endpoint)
      throws IOException {
    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      ListFeaturesRequest listFeaturesRequest =
          ListFeaturesRequest.newBuilder()
              .setParent(
                  EntityTypeName.of(project, location, featurestoreId, entityTypeId).toString())
              .build();
      System.out.println("List Features Response");
      for (Feature element :
          featurestoreServiceClient.listFeatures(listFeaturesRequest).iterateAll()) {
        System.out.println(element);
      }
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function listFeatures() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}`;

  const request = {
    parent: parent,
  };

  // List Features request
  const [response] = await featurestoreServiceClient.listFeatures(request, {
    timeout: Number(timeout),
  });

  console.log('List features response');
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
listFeatures();

Idiomas adicionales

Si deseas obtener información sobre cómo instalar y usar el SDK de Vertex AI para Python, consulta Cómo usar el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de IA de Vertex para Python.

Busca funciones

Busca atributos basados en una o más de sus propiedades, como el ID del atributo, el ID de tipo de entidad o la descripción del atributo. Vertex AI Feature Store (Legacy) busca en todos los almacenes de entidades y tipos de entidades en una ubicación determinada. También puedes limitar los resultados si filtras por featurestores, tipos de valor y etiquetas específicos.

Para enumerar todas las funciones, consulta la sección sobre Enumera funciones.

IU web

  1. En la sección de Vertex AI de la consola de Google Cloud, ve a la página Funciones.

    Ve a la página Atributos

  2. Selecciona una región de la lista desplegable Región.
  3. Haz clic en el campo Filtro de la tabla de funciones.
  4. Selecciona una propiedad para filtrar, como Función, que muestra atributos que contienen una string coincidente en cualquier parte de su ID.
  5. Escribe un valor para el filtro y presiona Intro. Vertex AI Feature Store (Legacy) muestra los resultados en la tabla de atributos.
  6. Para agregar filtros adicionales, vuelve a hacer clic en el campo Filtro.

REST

Para buscar atributos, envía una solicitud GET mediante el método featurestores.searchFeatures. En el siguiente ejemplo, se usan varios parámetros de búsqueda, escritos como featureId:test AND valueType=STRING. La consulta muestra atributos que contienen test en su ID y cuyos valores son del tipo STRING.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.

Método HTTP y URL:

GET https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores:searchFeatures?query="featureId:test%20AND%20valueType=STRING"

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores:searchFeatures?query="featureId:test%20AND%20valueType=STRING""

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores:searchFeatures?query="featureId:test%20AND%20valueType=STRING"" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "features": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_IDfeature-delete.html/featurestores/featurestore_demo/entityTypes/testing/features/test1",
      "description": "featurestore test1",
      "createTime": "2021-02-26T18:16:09.528185Z",
      "updateTime": "2021-02-26T18:16:09.528185Z",
      "labels": {
        "environment": "testing"
      }
    }
  ]
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.aiplatform.v1.Feature;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.SearchFeaturesRequest;
import java.io.IOException;

public class SearchFeaturesSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String query = "YOUR_QUERY";
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    searchFeaturesSample(project, query, location, endpoint);
  }

  static void searchFeaturesSample(String project, String query, String location, String endpoint)
      throws IOException {
    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      SearchFeaturesRequest searchFeaturesRequest =
          SearchFeaturesRequest.newBuilder()
              .setLocation(LocationName.of(project, location).toString())
              .setQuery(query)
              .build();
      System.out.println("Search Features Response");
      for (Feature element :
          featurestoreServiceClient.searchFeatures(searchFeaturesRequest).iterateAll()) {
        System.out.println(element);
      }
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function searchFeatures() {
  // Configure the locationResource resource
  const locationResource = `projects/${project}/locations/${location}`;

  const request = {
    location: locationResource,
    query: query,
  };

  // Search Features request
  const [response] = await featurestoreServiceClient.searchFeatures(request, {
    timeout: Number(timeout),
  });

  console.log('Search features response');
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
searchFeatures();

Idiomas adicionales

Si deseas obtener información sobre cómo instalar y usar el SDK de Vertex AI para Python, consulta Cómo usar el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de IA de Vertex para Python.

View feature details

Ver detalles sobre un atributo, como su tipo de valor o descripción. Si usas la consola de Google Cloud y tienes habilitada la supervisión de funciones, también puedes ver la distribución de los valores de las funciones en el tiempo.

IU web

  1. En la sección de Vertex AI de la consola de Google Cloud, ve a la página Funciones.

    Ve a la página Atributos

  2. Selecciona una región de la lista desplegable Región.
  3. En la tabla de atributos, consulta la columna Funciones para encontrar el elemento del que deseas ver los detalles.
  4. Haz clic en el nombre de un atributo para ver sus detalles.
  5. Para ver sus métricas, haz clic en Métricas. Vertex AI Feature Store (Legacy) proporciona métricas de distribución de atributos para la función.

REST

Para obtener detalles sobre un atributo, envía una solicitud GET mediante el método featurestores.entityTypes.features.get.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.
  • FEATURESTORE_ID: ID del featurestore.
  • ENTITY_TYPE_ID: ID del tipo de entidad.
  • FEATURE_ID: ID del atributo.

Método HTTP y URL:

GET https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID",
  "description": "DESCRIPTION",
  "valueType": "VALUE_TYPE",
  "createTime": "2021-03-01T22:41:20.628493Z",
  "updateTime": "2021-03-01T22:41:20.628493Z",
  "labels": {
    "environment": "testing"
  },
  "etag": "AMEw9yOZbdYKHTyjV22ziZR1vUX3nWOi0o2XU3-OADahSdfZ8Apklk_qPruhF-o1dOSD",
  "monitoringConfig": {}
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.aiplatform.v1.Feature;
import com.google.cloud.aiplatform.v1.FeatureName;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import com.google.cloud.aiplatform.v1.GetFeatureRequest;
import java.io.IOException;

public class GetFeatureSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    String featureId = "YOUR_FEATURE_ID";
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";

    getFeatureSample(project, featurestoreId, entityTypeId, featureId, location, endpoint);
  }

  static void getFeatureSample(
      String project,
      String featurestoreId,
      String entityTypeId,
      String featureId,
      String location,
      String endpoint)
      throws IOException {

    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      GetFeatureRequest getFeatureRequest =
          GetFeatureRequest.newBuilder()
              .setName(
                  FeatureName.of(project, location, featurestoreId, entityTypeId, featureId)
                      .toString())
              .build();

      Feature feature = featurestoreServiceClient.getFeature(getFeatureRequest);
      System.out.println("Get Feature Response");
      System.out.println(feature);
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const featureId = 'YOUR_FEATURE_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function getFeature() {
  // Configure the name resource
  const name = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}/features/${featureId}`;

  const request = {
    name: name,
  };

  // Get Feature request
  const [response] = await featurestoreServiceClient.getFeature(request, {
    timeout: Number(timeout),
  });

  console.log('Get feature response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
getFeature();

Idiomas adicionales

Si deseas obtener información sobre cómo instalar y usar el SDK de Vertex AI para Python, consulta Cómo usar el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de IA de Vertex para Python.

Borra un atributo

Borrar una función y todos sus valores

IU web

  1. En la sección de Vertex AI de la consola de Google Cloud, ve a la página Funciones.

    Ve a la página Atributos

  2. Selecciona una región de la lista desplegable Región.
  3. En la tabla de atributos, consulta la columna Función y busca el atributo que deseas borrar.
  4. Haz clic en el nombre de la función.
  5. En la barra de acciones, haz clic en Borrar.
  6. Haz clic en Confirmar para borrar la función y sus valores.

REST

Para borrar una función, envía una solicitud BORRAR mediante el método featurestores.entityTypes.features.delete.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • LOCATION_ID: Región donde se encuentra el featurestore, como us-central1.
  • PROJECT_ID: El ID del proyecto.
  • FEATURESTORE_ID: ID del featurestore.
  • ENTITY_TYPE_ID: ID del tipo de entidad.
  • FEATURE_ID: ID del atributo.

Método HTTP y URL:

DELETE https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/entityTypes/ENTITY_TYPE_ID/features/FEATURE_ID" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featurestores/FEATURESTORE_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeleteOperationMetadata",
    "genericMetadata": {
      "createTime": "2021-02-26T17:32:56.008325Z",
      "updateTime": "2021-02-26T17:32:56.008325Z"
    }
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.DeleteFeatureRequest;
import com.google.cloud.aiplatform.v1.DeleteOperationMetadata;
import com.google.cloud.aiplatform.v1.FeatureName;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceClient;
import com.google.cloud.aiplatform.v1.FeaturestoreServiceSettings;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteFeatureSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String featurestoreId = "YOUR_FEATURESTORE_ID";
    String entityTypeId = "YOUR_ENTITY_TYPE_ID";
    String featureId = "YOUR_FEATURE_ID";
    String location = "us-central1";
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    int timeout = 300;

    deleteFeatureSample(
        project, featurestoreId, entityTypeId, featureId, location, endpoint, timeout);
  }

  static void deleteFeatureSample(
      String project,
      String featurestoreId,
      String entityTypeId,
      String featureId,
      String location,
      String endpoint,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    FeaturestoreServiceSettings featurestoreServiceSettings =
        FeaturestoreServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (FeaturestoreServiceClient featurestoreServiceClient =
        FeaturestoreServiceClient.create(featurestoreServiceSettings)) {

      DeleteFeatureRequest deleteFeatureRequest =
          DeleteFeatureRequest.newBuilder()
              .setName(
                  FeatureName.of(project, location, featurestoreId, entityTypeId, featureId)
                      .toString())
              .build();

      OperationFuture<Empty, DeleteOperationMetadata> operationFuture =
          featurestoreServiceClient.deleteFeatureAsync(deleteFeatureRequest);
      System.out.format("Operation name: %s%n", operationFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      operationFuture.get(timeout, TimeUnit.SECONDS);
      System.out.format("Deleted Feature.");
      featurestoreServiceClient.close();
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const project = 'YOUR_PROJECT_ID';
// const featurestoreId = 'YOUR_FEATURESTORE_ID';
// const entityTypeId = 'YOUR_ENTITY_TYPE_ID';
// const featureId = 'YOUR_FEATURE_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const apiEndpoint = 'YOUR_API_ENDPOINT';
// const timeout = <TIMEOUT_IN_MILLI_SECONDS>;

// Imports the Google Cloud Featurestore Service Client library
const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: apiEndpoint,
};

// Instantiates a client
const featurestoreServiceClient = new FeaturestoreServiceClient(
  clientOptions
);

async function deleteFeature() {
  // Configure the name resource
  const name = `projects/${project}/locations/${location}/featurestores/${featurestoreId}/entityTypes/${entityTypeId}/features/${featureId}`;

  const request = {
    name: name,
  };

  // Delete Feature request
  const [operation] = await featurestoreServiceClient.deleteFeature(request, {
    timeout: Number(timeout),
  });
  const [response] = await operation.promise();

  console.log('Delete feature response');
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
deleteFeature();

Idiomas adicionales

Si deseas obtener información sobre cómo instalar y usar el SDK de Vertex AI para Python, consulta Cómo usar el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación de referencia del SDK de IA de Vertex para Python.

¿Qué sigue?