Mengelola skema dokumen

Dokumen ini menjelaskan cara mengelola skema dokumen di Document AI Warehouse, termasuk operasi pembuatan, pengambilan, pencantuman, pembaruan, dan penghapusan.

Apa itu skema dokumen

Setiap dokumen memiliki jenis dokumen tertentu dan ditentukan oleh skema.

Skema dokumen menentukan struktur untuk jenis dokumen (misalnya, Invoice atau Slip Gaji) di Document AI Warehouse, tempat admin dapat menentukan Properti dari berbagai jenis data (Teks | Numerik | Tanggal | Enumerasi).

Properti digunakan untuk merepresentasikan data yang diekstrak, tag klasifikasi, atau tag bisnis lainnya yang ditambahkan ke dokumen oleh AI atau pengguna manusia - misalnya, Invoice_Amount (numerik), Due_Date (tanggal), atau Supplier_Name (teks).

  1. Atribut Properti: Setiap properti dapat dideklarasikan sebagai

    1. Dapat difilter - dapat digunakan untuk memfilter hasil penelusuran

    2. Dapat ditelusuri - diindeks sehingga dapat ditemukan dalam kueri penelusuran

    3. Wajib - required digunakan untuk memastikan properti ada dalam dokumen (Sebaiknya simpan sebagian besar properti sebagai required = false, kecuali properti tersebut wajib ada.)

  2. Skema yang Dapat Diperluas: dalam beberapa kasus, pengguna akhir dengan akses Edit perlu menambahkan / menghapus properti skema baru ke dokumen. Hal ini didukung oleh "properti MAP", yang merupakan daftar pasangan nilai kunci.

    1. Setiap key-value pair dalam properti MAP dapat berupa jenis data (Teks | Numerik | Tanggal | Enumerasi).

    2. Misalnya, Invoice dapat berisi Properti Peta "Invoice_Entities" dengan pasangan nilai kunci berikut:

      • Invoice_Amount (numerik) 1000

      • Due_Date (date) 24/12/2021

      • Supplier_Name (text) ABC Corp

    3. Tidak Dapat Diubahnya Skema: Perhatikan bahwa Skema atau Properti Skema dapat ditambahkan, tetapi saat ini tidak dapat diedit atau dihapus, jadi tentukan skema dengan cermat.

Sebelum memulai

Sebelum memulai, pastikan Anda telah menyelesaikan halaman Mulai Cepat.

Membuat skema

Buat skema dokumen.

REST

  curl --location --request POST --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas \
  --header "Content-Type: application/json" \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --data '{
    "display_name": "Test Doc Schema",
    "property_definitions": [
      {
        "name": "plaintiff",
        "display_name": "Plaintiff",
        "is_searchable": true,
        "is_repeatable": true,
        "text_type_options": {}
      }
    ]
  }'

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = 'YOUR_PROJECT_NUMBER'
# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'


def sample_create_document_schema(project_number: str, location: str) -> None:
    """Creates document schema.

    Args:
        project_number: Google Cloud project number.
        location: Google Cloud project location.
    Returns:
        Response object.
    """
    # Create a Schema Service client.
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    property_definition = contentwarehouse.PropertyDefinition(
        name="stock_symbol",  # Must be unique within a document schema (case insensitive)
        display_name="Searchable text",
        is_searchable=True,
        text_type_options=contentwarehouse.TextTypeOptions(),
    )
    # Initialize request argument(s)
    document_schema = contentwarehouse.DocumentSchema(
        display_name="My Test Schema",
        property_definitions=[property_definition],
    )

    request = contentwarehouse.CreateDocumentSchemaRequest(
        # The full resource name of the location, e.g.:
        # projects/{project_number}/locations/{location}/
        parent=document_schema_client.common_location_path(project_number, location),
        document_schema=document_schema,
    )

    # Make the request
    response = document_schema_client.create_document_schema(request=request)

    # Print response
    print("Document Schema Created:", response)

    return response

Java

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.contentwarehouse.v1.CreateDocumentSchemaRequest;
import com.google.cloud.contentwarehouse.v1.DocumentSchema;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceSettings;
import com.google.cloud.contentwarehouse.v1.LocationName;
import com.google.cloud.contentwarehouse.v1.PropertyDefinition;
import com.google.cloud.contentwarehouse.v1.TextTypeOptions;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class CreateDocumentSchema {

  public static void createDocumentSchema() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    createDocumentSchema(projectId, location);
  }

  // Creates a new Document Schema
  public static void createDocumentSchema(String projectId, String location) throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
         DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Schema Service client
    try (DocumentSchemaServiceClient documentSchemaServiceClient =
        DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {
      /*  The full resource name of the location, e.g.:
      projects/{project_number}/locations/{location} */
      String parent = LocationName.format(projectNumber, location);

      /* Create Document Schema with Text Type Property Definition
       * More detail on managing Document Schemas: 
       * https://cloud.google.com/document-warehouse/docs/manage-document-schemas */
      DocumentSchema documentSchema = DocumentSchema.newBuilder()
          .setDisplayName("Test Doc Schema")
          .setDescription("Test Doc Schema's Description")
          .addPropertyDefinitions(
            PropertyDefinition.newBuilder()
              .setName("plaintiff")
              .setDisplayName("Plaintiff")
              .setIsSearchable(true)
              .setIsRepeatable(true)
              .setTextTypeOptions(TextTypeOptions.newBuilder().build())
              .build()).build();

      // Define Document Schema request
      CreateDocumentSchemaRequest createDocumentSchemaRequest =
          CreateDocumentSchemaRequest.newBuilder()
            .setParent(parent)
            .setDocumentSchema(documentSchema).build();

      // Create Document Schema
      DocumentSchema documentSchemaResponse =
          documentSchemaServiceClient.createDocumentSchema(createDocumentSchemaRequest); 

      System.out.println(documentSchemaResponse.getName());
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


/**
 * TODO(developer): Uncomment these variables before running the sample.
 * const projectNumber = 'YOUR_PROJECT_NUMBER';
 * const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
 */

// Import from google cloud
const {DocumentSchemaServiceClient} =
  require('@google-cloud/contentwarehouse').v1;

const apiEndpoint =
  location === 'us'
    ? 'contentwarehouse.googleapis.com'
    : `${location}-contentwarehouse.googleapis.com`;

// Create service client
const serviceClient = new DocumentSchemaServiceClient({
  apiEndpoint: apiEndpoint,
});

// Create Document Schema
async function createDocumentSchema() {
  // The full resource name of the location, e.g.:
  // projects/{project_number}/locations/{location}
  const parent = `projects/${projectNumber}/locations/${location}`;
  // Initialize request argument(s)
  const request = {
    parent: parent,
    // Document Schema
    documentSchema: {
      displayName: 'My Test Schema',
      // Property Definition
      propertyDefinitions: [
        {
          name: 'testPropertyDefinitionName', // Must be unique within a document schema (case insensitive)
          displayName: 'searchable text',
          isSearchable: true,
          textTypeOptions: {},
        },
      ],
    },
  };

  // Make Request
  const response = serviceClient.createDocumentSchema(request);

  // Print out response
  response.then(
    result =>
      console.log(`Document Schema Created: ${JSON.stringify(result)}`),
    error => console.log(`${error}`)
  );
}

Mendapatkan skema

Mendapatkan detail skema dokumen.

REST

  curl --request GET --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/{document_schema_id} \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --header "Content-Type: application/json; charset=UTF-8"

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = 'YOUR_PROJECT_NUMBER'
# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'
# document_schema_id = "YOUR_DOCUMENT SCHEMA_ID"


def sample_get_document_schema(
    project_number: str, location: str, document_schema_id: str
) -> None:
    """Gets document schema details.

    Args:
        project_number: Google Cloud project number.
        location: Google Cloud project location.
        document_schema_id: Unique identifier for document schema
    Returns:
        Response object.
    """
    # Create a Schema Service client.
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}
    document_schema_path = document_schema_client.document_schema_path(
        project=project_number,
        location=location,
        document_schema=document_schema_id,
    )

    # Initialize request argument(s)
    request = contentwarehouse.GetDocumentSchemaRequest(
        name=document_schema_path,
    )

    # Make the request
    response = document_schema_client.get_document_schema(request=request)

    # Handle the response
    print("Document Schema:", response)

    return response

Java

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.contentwarehouse.v1.DocumentSchema;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaName;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceSettings;
import com.google.cloud.contentwarehouse.v1.GetDocumentSchemaRequest;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class GetDocumentSchema {

  public static void getDocumentSchema() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String documentSchemaId = "your-document-schema-id";
    getDocumentSchema(projectId, location, documentSchemaId);
  }

  // Retrieves details about existing Document Schema
  public static void getDocumentSchema(String projectId, String location, 
        String documentSchemaId) throws IOException, 
            InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
         DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Schema Service client
    try (DocumentSchemaServiceClient documentSchemaServiceClient =
        DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {
      /* The full resource name of the location, e.g.: 
       projects/{project_number}/location/{location}/documentSchemas/{document_schema_id} */
      DocumentSchemaName documentSchemaName = 
          DocumentSchemaName.of(projectNumber, location, documentSchemaId);

      // Define request to get details of a specific Document Schema
      GetDocumentSchemaRequest getDocumentSchemaRequest = 
          GetDocumentSchemaRequest.newBuilder().setName(documentSchemaName.toString()).build();

      // Get details of Document Schema
      DocumentSchema documentSchema = 
          documentSchemaServiceClient.getDocumentSchema(getDocumentSchemaRequest);

      System.out.println(documentSchema.getName());
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


/**
 * TODO(developer): Uncomment these variables before running the sample.
 * const projectNumber = 'YOUR_PROJECT_NUMBER';
 * const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
 * const schemaId = 'YOUR_DOCUMENT_SCHEMA_ID';
 */

// Import from google cloud
const {DocumentSchemaServiceClient} =
  require('@google-cloud/contentwarehouse').v1;

const apiEndpoint =
  location === 'us'
    ? 'contentwarehouse.googleapis.com'
    : `${location}-contentwarehouse.googleapis.com`;

// Create service client
const serviceClient = new DocumentSchemaServiceClient({
  apiEndpoint: apiEndpoint,
});

// Get Document Schema
async function getDocumentSchema() {
  // Initialize request argument(s)
  const request = {};

  // The full resource name of the location, e.g.:
  // projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}
  const name = serviceClient.documentSchemaPath(
    projectNumber,
    location,
    documentSchemaId
  );
  request.name = name;

  // Make Request
  const response = serviceClient.getDocumentSchema(request);

  // Print out response
  response.then(
    result => console.log(`Schema Found: ${JSON.stringify(result)}`),
    error => console.log(`${error}`)
  );
}

Mencantumkan skema

Mencantumkan skema dokumen.

REST

  curl --request GET --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --header "Content-Type: application/json; charset=UTF-8"

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = 'YOUR_PROJECT_NUMBER'
# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'


def sample_list_document_schemas(project_number: str, location: str) -> None:
    """Lists document schemas.

    Args:
        project_number: Google Cloud project number.
        location: Google Cloud project location.
    """
    # Create a client
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}
    parent = document_schema_client.common_location_path(
        project=project_number, location=location
    )

    # Initialize request argument(s)
    request = contentwarehouse.ListDocumentSchemasRequest(
        parent=parent,
    )

    # Make the request
    page_result = document_schema_client.list_document_schemas(request=request)

    # Print response
    responses = []
    print("Document Schemas:")
    for response in page_result:
        print(response)
        responses.append(response)

    return responses

Java

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.contentwarehouse.v1.DocumentSchema;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceSettings;
import com.google.cloud.contentwarehouse.v1.ListDocumentSchemasRequest;
import com.google.cloud.contentwarehouse.v1.LocationName;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ListDocumentSchema {
  public static void listDocumentSchemas() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    listDocumentSchemas(projectId, location);
  }

  // Retrieves all Document Schemas associated with a specified project
  public static void listDocumentSchemas(String projectId, String location) throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
         DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Schema Service client
    try (DocumentSchemaServiceClient documentSchemaServiceClient =
        DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {
      /*  The full resource name of the location, e.g.:
      projects/{project_number}/locations/{location} */
      String parent = LocationName.format(projectNumber, location);

      // Define request to list all Document Schemas
      ListDocumentSchemasRequest listDocumentSchemasRequest = 
          ListDocumentSchemasRequest.newBuilder().setParent(parent).build();

      // Print each schema ID  
      for (DocumentSchema schema :
          documentSchemaServiceClient.listDocumentSchemas(listDocumentSchemasRequest)
            .iterateAll()) {
        System.out.println(schema.getName());
      }
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Menghapus skema

Menghapus skema dokumen.

REST

  curl --request DELETE --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/{document_schema_id} \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --header "Content-Type: application/json; charset=UTF-8"

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = 'YOUR_PROJECT_NUMBER'
# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'
# document_schema_id = "YOUR_DOCUMENT SCHEMA_ID"


def sample_delete_document_schema(
    project_number: str, location: str, document_schema_id: str
) -> None:
    """Deletes document schema.

    Args:
        project_number: Google Cloud project number.
        location: Google Cloud project location.
        document_schema_id: Unique identifier for document schema
    Returns:
        None, if operation is successful
    """
    # Create a client
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}
    document_schema_path = document_schema_client.document_schema_path(
        project=project_number,
        location=location,
        document_schema=document_schema_id,
    )

    # Initialize request argument(s)
    request = contentwarehouse.DeleteDocumentSchemaRequest(
        name=document_schema_path,
    )

    # Make the request
    response = document_schema_client.delete_document_schema(request=request)

    return response

Java

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.contentwarehouse.v1.DeleteDocumentSchemaRequest;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaName;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceSettings;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class DeleteDocumentSchema {

  public static void createDocumentSchema() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String documentSchemaId = "your-schema-id";
    deleteDocumentSchema(projectId, location, documentSchemaId);
  }

  // Creates a new Document Schema
  public static void deleteDocumentSchema(String projectId, String location,
      String documentSchemaId) throws IOException,
          InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
         DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Schema Service client
    try (DocumentSchemaServiceClient documentSchemaServiceClient =
        DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {

      /* The full resource name of the location, e.g.: 
       projects/{project_number}/location/{location}/documentSchemas/{document_schema_id} */
      DocumentSchemaName documentSchemaName = 
          DocumentSchemaName.of(projectNumber, location, documentSchemaId);

      /* Create request to delete Document Schema from provided schema ID.
       * More detail on managing Document Schemas: 
       * https://cloud.google.com/document-warehouse/docs/manage-document-schemas */
      DeleteDocumentSchemaRequest deleteDocumentSchemaRequest = 
          DeleteDocumentSchemaRequest.newBuilder()
            .setName(documentSchemaName.toString()).build();

      // Delete Document Schema
      documentSchemaServiceClient.deleteDocumentSchema(deleteDocumentSchemaRequest);

      System.out.println("Document Schema ID " + documentSchemaId + " has been deleted.");

    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


/**
 * TODO(developer): Uncomment these variables before running the sample.
 * const projectId = 'YOUR_PROJECT_ID';
 * const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
 * const documentSchemaId = 'YOUR_DOCUMENT_SCHEMA_ID';
 */

// Import from google cloud

const {DocumentSchemaServiceClient} =
  require('@google-cloud/contentwarehouse').v1;

const apiEndpoint =
  location === 'us'
    ? 'contentwarehouse.googleapis.com'
    : `${location}-contentwarehouse.googleapis.com`;

// Create service client
const serviceClient = new DocumentSchemaServiceClient({
  apiEndpoint: apiEndpoint,
});

// Delete Document Schema
async function deleteDocumentSchema() {
  // Initialize request argument(s)
  const request = {
    // The full resource name of the location, e.g.:
    // projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}
    name: `projects/${projectId}/locations/${location}/documentSchemas/${documentSchemaId}`,
  };

  // Make Request
  const response = await serviceClient.deleteDocumentSchema(request);

  // Print out response
  console.log(`Document Schema Deleted: ${JSON.stringify(response)}`);
}

Memperbarui skema

Memperbarui skema dokumen. Saat ini, logika pembaruan hanya mendukung penambahan definisi properti baru. Skema dokumen baru harus menyertakan semua definisi properti yang ada dalam skema yang ada.

  • Didukung:

    • Untuk properti yang ada, pengguna dapat mengubah setelan metadata berikut: is_repeatable, is_metadata, is_required.
    • Untuk properti ENUM yang ada, pengguna dapat menambahkan kemungkinan nilai ENUM baru atau menghapus kemungkinan nilai ENUM yang ada. Mereka dapat memperbarui flag EnumTypeOptions.validation_check_disabled untuk menonaktifkan pemeriksaan validasi. Pemeriksaan validasi digunakan untuk memastikan nilai ENUM yang ditentukan dalam dokumen berada dalam rentang kemungkinan nilai ENUM yang ditentukan dalam definisi properti saat memanggil CreateDocument API.
    • Menambahkan definisi properti baru didukung.
  • Tidak didukung:

    • Untuk skema yang ada, update ke display_name dan document_is_folder tidak diizinkan.
    • Untuk properti yang sudah ada, pembaruan pada name, display_name, dan value_type_options tidak diizinkan.

REST

curl --request PATCH --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/{document_schema_id} \
--header "Authorization: Bearer $(gcloud auth print-access-token)" \
--header "Content-Type: application/json; charset=UTF-8" \
--data '{
  "document_schema": {
    "display_name": "Test Doc Schema",
    "property_definitions": [
      {
        "name": "plaintiff",
        "display_name": "Plaintiff",
        "is_repeatable": true,
        "text_type_options": {}
      }
    ]
  }
}'

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"
# location = "us" # Format is 'us' or 'eu'
# document_schema_id = "YOUR_SCHEMA_ID"


def update_document_schema(
    project_number: str, location: str, document_schema_id: str
) -> None:
    # Create a Schema Service client
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}
    document_schema_path = document_schema_client.document_schema_path(
        project=project_number,
        location=location,
        document_schema=document_schema_id,
    )

    # Define Schema Property of Text Type with updated values
    updated_property_definition = contentwarehouse.PropertyDefinition(
        name="stock_symbol",  # Must be unique within a document schema (case insensitive)
        display_name="Searchable text",
        is_searchable=True,
        is_repeatable=False,
        is_required=True,
        text_type_options=contentwarehouse.TextTypeOptions(),
    )

    # Define Update Document Schema Request
    update_document_schema_request = contentwarehouse.UpdateDocumentSchemaRequest(
        name=document_schema_path,
        document_schema=contentwarehouse.DocumentSchema(
            display_name="My Test Schema",
            property_definitions=[updated_property_definition],
        ),
    )

    # Update Document schema
    updated_document_schema = document_schema_client.update_document_schema(
        request=update_document_schema_request
    )

    # Read the output
    print(f"Updated Document Schema: {updated_document_schema}")

Java

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI Warehouse.

Untuk melakukan autentikasi ke Document AI Warehouse, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.contentwarehouse.v1.DocumentSchema;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaName;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentSchemaServiceSettings;
import com.google.cloud.contentwarehouse.v1.PropertyDefinition;
import com.google.cloud.contentwarehouse.v1.TextTypeOptions;
import com.google.cloud.contentwarehouse.v1.UpdateDocumentSchemaRequest;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class UpdateDocumentSchema {
  public static void updateDocumentSchema() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException { 
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String documentSchemaId = "your-document-schema-id";
    /* The below method call retrieves details about the schema you are about to update.
     * It is important to note that some properties cannot be edited or removed. 
     * For more information on managing document schemas, please see the below documentation.
     * https://cloud.google.com/document-warehouse/docs/manage-document-schemas */
    GetDocumentSchema.getDocumentSchema(projectId, location, documentSchemaId);
    updateDocumentSchema(projectId, location, documentSchemaId);
  }

  // Updates an existing Document Schema
  public static void updateDocumentSchema(String projectId, String location, 
        String documentSchemaId) throws IOException, InterruptedException,
          ExecutionException, TimeoutException { 
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }

    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
             DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    /* Create the Schema Service Client 
     * Initialize client that will be used to send requests. 
     * This client only needs to be created once, and can be reused for multiple requests. */
    try (DocumentSchemaServiceClient documentSchemaServiceClient = 
            DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {

      /* The full resource name of the location, e.g.: 
       projects/{project_number}/location/{location}/documentSchemas/{document_schema_id} */
      DocumentSchemaName documentSchemaName = 
          DocumentSchemaName.of(projectNumber, location, documentSchemaId);

      // Define the new Schema Property with updated values
      PropertyDefinition propertyDefinition = PropertyDefinition.newBuilder()
          .setName("plaintiff")
          .setDisplayName("Plaintiff")
          .setIsSearchable(true)
          .setIsRepeatable(true)
          .setIsRequired(false)
          .setTextTypeOptions(TextTypeOptions.newBuilder()
          .build())
          .build();

      DocumentSchema updatedDocumentSchema = DocumentSchema.newBuilder()
                    .setDisplayName("Test Doc Schema") 
                    .addPropertyDefinitions(0, propertyDefinition).build();

      // Create the Request to Update the Document Schema
      UpdateDocumentSchemaRequest updateDocumentSchemaRequest = 
            UpdateDocumentSchemaRequest.newBuilder()
            .setName(documentSchemaName.toString())
            .setDocumentSchema(updatedDocumentSchema)
            .build();

      // Update Document Schema
      updatedDocumentSchema = 
        documentSchemaServiceClient.updateDocumentSchema(updateDocumentSchemaRequest);

      // Read the output of Updated Document Schema Name
      System.out.println(updatedDocumentSchema.getName());
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Langkah berikutnya