ArcGIS Desktop

  • ArcGIS Pro
  • ArcMap

  • My Profile
  • Ayuda
  • Sign Out
ArcGIS Desktop

ArcGIS Online

La plataforma de representación cartográfica para tu organización

ArcGIS Desktop

Un completo SIG profesional

ArcGIS Enterprise

SIG en tu empresa

ArcGIS Developers

Herramientas para crear aplicaciones basadas en la ubicación

ArcGIS Solutions

Plantillas de aplicaciones y mapas gratuitas para tu sector

ArcGIS Marketplace

Obtén aplicaciones y datos para tu organización.

  • Documentación
  • Soporte
Esri
  • Iniciar sesión
user
  • Mi perfil
  • Cerrar sesión

ArcMap

  • Inicio
  • Introducción
  • Cartografiar
  • Analizar
  • Administrar datos
  • Herramientas
  • Extensiones

Conciliar y publicar de forma automática las operaciones de datos habilitados para la sincronización

  • Identificar las versiones de geodatabase en función del nombre del servicio
  • Conciliar versiones y publicar cambios por lotes
  • Comprimir la geodatabase
  • Reconstruir índices y actualizar estadísticas
  • Eliminar versiones conciliadas
  • Ejemplo de código completo

Los administradores de geodatabases de ArcGIS pueden utilizar scripts de Python para automatizar muchas tareas que normalmente se realizan utilizando varias herramientas de geoprocesamiento. En este tema se explica el proceso que debe seguir un administrador para ejecutar una conciliación nocturna programada de las versiones, una vez que los trabajadores de campo hayan sincronizado las ediciones realizadas en los datos que participan en el versionado tradicional.

Identificar las versiones de geodatabase en función del nombre del servicio

Primero, cree una lista de las versiones de la geodatabase que se deben conciliar.

# Create a list of user names that will be used to find versions.
userList = ['???', '###']
# Get a list of versions for the service named '???' and '###' to pass into the ReconcileVersions tool.
versions = arcpy.da.ListVersions('//connectionLocation/admin.sde')
# Create an empty list that will be used to hold version names that you want to reconcile.
verReconcileList = []
# Loop through the versions list to look for versions with appropriate names.
# if these names are found append them to the verReconcileList.
for user in userList:
    for version in versions:
        if user.lower() in version.name.lower():
            verReconcileList.append(version.name)

Conciliar versiones y publicar cambios por lotes

Puede utilizar la herramienta Conciliar versiones para conciliar y publicar todas las versiones tradicionales de una geodatabase corporativa. Esta herramienta proporciona opciones para conciliar todas las versiones de la geodatabase en una versión de destino (ALL_VERSIONS) o solo las versiones que impiden que la versión de destino se comprima (BLOCKING_VERSIONS). Esta herramienta es un medio para obtener una compresión eficaz, ya que permite conciliar y publicar varias versiones al mismo tiempo en una secuencia adecuada. Tras las operaciones de conciliación o publicación, las versiones también se pueden eliminar proporcionando la palabra clave DELETE_VERSION.

En este ejemplo, las versiones no se eliminan (se proporciona la palabra clave KEEP_VERSION) y la herramienta se ejecuta como administrador de la geodatabase. Conectarse como administrador de la geodatabase proporciona capacidad para conciliar y publicar todas las versiones en la geodatabase, incluidas las versiones privadas o protegidas que sean de propiedad de otros usuarios.

# Get a list of versions to pass into the ReconcileVersions tool. versionList = arcpy.ListVersions('//connectionLocation/admin.sde')
# Execute the ReconcileVersions tool.
arcpy.ReconcileVersions_management('//connectionLocation/admin.sde', "ALL_VERSIONS", "sde.DEFAULT", verReconcileList, "LOCK_ACQUIRED", "NO_ABORT", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST", "KEEP_VERSION", "c:/temp/reconcilelog.txt")

Comprimir la geodatabase

Después de la conciliación y la publicación de los cambios, es importante comprimir la geodatabase para eliminar cualquier información redundante y mover las ediciones a las tablas base.

# Run the compress tool. 
arcpy.Compress_management('//connectionLocation/admin.sde')

Reconstruir índices y actualizar estadísticas

Después de realizar una operación de compresión, se recomienda reconstruir los índices y actualizar las estadísticas. Estos pasos se pueden llevar a cabo con las herramientas Reconstruir índices y Analizar datasets. Estas herramientas permiten introducir una lista de datasets y utilizar sus funciones en todos los datasets a la vez. Estas herramientas también actualizan las estadísticas y regeneran los índices de las tablas de sistema pertinentes cuando se ejecutan como administrador de la geodatabase. La primera parte del proceso consiste en obtener una lista de datos y de los usuarios que son propietarios de ellos. Solo el propietario de los datos puede actualizar los índices y las estadísticas.

# set the workspace arcpy.env.workspace = '//connectionLocation/dataOwner.sde'
# Get the user name for the workspace
# this assumes you are using database authentication. # OS authentication connection files do not have a 'user' property. userName = arcpy.Describe(arcpy.env.workspace).connectionProperties.user
# Get a list of all the datasets the user has access to. # First, get all the stand-alone tables, feature classes and rasters owned by the current user. oDataList = arcpy.ListTables('*.' + userName + '.*') + arcpy.ListFeatureClasses('*.' + userName + '.*') + arcpy.ListRasters('*.' + userName + '.*')
# Next, for feature datasets owned by the current user
# get all of the featureclasses and add them to the master list. for dataset in arcpy.ListDatasets('*.' + userName + '.*'):
    oDataList += arcpy.ListFeatureClasses(feature_dataset=dataset)
Nota:

Los tokens con comodines que se utilizan para limitar los datasets que pertenecen al usuario dependen del sistema operativo. En el ejemplo anterior, ('*.' + userName + '.*') funcionará para geodatabases en Microsoft SQL Server, PostgreSQL y IBM Db2. Para geodatabases de Oracle, se puede utilizar el siguiente comodín: (userName + '.*').

Una vez que se identifique la lista de los datos propiedad de cada usuario, utilice dicha información en las herramientas Reconstruir índices y Analizar datasets.

Si hay más de un propietario de datos, genere una lista de datos para cada propietario de datos y ejecute las herramientas Reconstruir índices y Analizar datasets con archivos de conexión de base de datos (.sde) que se conecten a la geodatabase como cada usuario.

# Execute rebuild indexes and analyze datasets
# Note: to use the "SYSTEM" option, the user must be an administrator.
workspace = "//connectionLocation/user1.sde"
arcpy.RebuildIndexes_management(workspace, "NO_SYSTEM", oDataList, "ALL")
arcpy.AnalyzeDatasets_management(workspace, "NO_SYSTEM", oDataList, "ANALYZE_BASE", "ANALYZE_DELTA", "ANALYZE_ARCHIVE")

Eliminar versiones conciliadas

El paso final del proceso es eliminar las versiones que se han conciliado y publicado. Anteriormente, obtuvo la lista de versiones conciliadas cuando ejecutó la sentencia versionList. En el siguiente código, recorrerá esta lista para eliminar cualquier versión que sea seguro eliminar.

Nota:

Si utiliza la replicación de geodatabase, es importante evitar eliminar cualquier versión a la que la réplica siga haciendo referencia. Son las versiones a partir de las cuales se crean las réplicas de la geodatabase. Utilice la función ListReplicas para enumerar las réplicas y el nombre de la versión a la que la réplica hace referencia. Intentar eliminar una versión de réplica resultará en un error, por lo que es mejor evitarlo.

En el siguiente ejemplo, obtendrá una lista de las versiones de réplica iterando a través de todas las réplicas. A continuación, elimine cualquiera de las versiones de réplica de la lista de versiones que se haya conciliado. Finalmente, recorra el resto de la lista de versiones conciliadas y dichas versiones.

# set the workspace workspace = '//connectionLocation/admin.sde'
# Get a list of all the replica versions in the geodatabase replicaVersions = [replica.version for replica in arcpy.da.ListReplicas(workspace)]
# Loop through this replica version list and remove these version names from the list of versions you reconciled earlier. # You want to remove versions from this list that are still being referenced by a replica for replicaVer in replicaVersions:
  if replicaVer in verReconcileList:
    verReconcileList.remove(replicaVer)
# Loop through the verReconcileList and delete versions. 
# These versions are no longer being referenced by a replica so you can assume it's safe to delete them. if len(versionsList) > 0:
  for version in verReconcileList:
  		arcpy.DeleteVersion_management(workspace, version)

Ejemplo de código completo

El siguiente ejemplo de código pone todas las piezas anterior juntas para realizar las siguientes operaciones:

  • Identifique las versiones de geodatabase.
  • Conciliar versiones y publicar cambios.
  • Comprima la geodatabase.
  • Reconstruir los índices y actualizar las estadísticas en las tablas del sistema.
  • Reconstruya los índices y actualice las estadísticas en las tablas de usuarios.

Nota:

El siguiente script contiene lógica adicional cuando se compara con las otras muestras de código en este tema. La lógica adicional está pensada para manejar mejor los casos de error. Tenga en cuenta también que algunos de los comentarios y nombres de variables se han cambiado en el script.

import arcpy

try:
    # Set the workspace 
    arcpy.env.workspace = 'Database Connections/admin.sde'
    
    # Set variables
    workspace = arcpy.env.workspace
    arcpy.env.overwriteOutput = True
    targetVersion = 'sde.DEFAULT'
    
    # Create a list of user names that will be used to find versions.
    userList = ['???', '###']
    
    # Get a list of versions for the service named '???' and '###' to pass into the ReconcileVersions tool.
    versions = arcpy.da.ListVersions(workspace)
    
    # Create an empty list to hold version names to reconcile.
    verReconcileList = []
    
    # Loop through the list to look for versions with our user names in their name where the parent version is the target version.
    # if these names are found, append them to the verReconcileList.
    for user in userList:
        for version in versions:
            if user.lower() in version.name.lower():
                if version.parentVersionName.lower() == targetVersion.lower():
                    verReconcileList.append(version.name)
    
    # Perform maintenance if versions are found; otherwise, there is no maintenance to perform.
    if len(verReconcileList)>0:
        
        # Execute the ReconcileVersions tool.
        arcpy.ReconcileVersions_management(workspace, "ALL_VERSIONS", targetVersion, verReconcileList, "LOCK_ACQUIRED", "NO_ABORT", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST", "KEEP_VERSION", "c:/temp/reconcilelog.txt")
        
        # Run the compress tool. 
        arcpy.Compress_management(workspace)
        
        # Rebuild indexes and analyze the states and states_lineages system tables
        arcpy.RebuildIndexes_management(workspace, "SYSTEM", "", "ALL")
        
        arcpy.AnalyzeDatasets_management(workspace, "SYSTEM", "", "ANALYZE_BASE", "ANALYZE_DELTA", "ANALYZE_ARCHIVE")
        
        
        '''
        *********************
        Data Owner(s) Section
        *********************
        '''
        # Get a list of datasets owned by the data owner user (requires second connection file)
        
        # Set the workspace 
        arcpy.env.workspace = 'Database Connections/dataOwner.sde'
        
        # Set a variable for the workspace
        workspace = arcpy.env.workspace
        
        # Get the user name for the workspace
        # this assumes you are using database authentication.
        # OS authentication connection files do not have a 'user' property.
        userName = arcpy.Describe(arcpy.env.workspace).connectionProperties.user
        
        # Get a list of all the datasets the user has access to.
        # First, get all the stand alone tables, feature classes and raster datasets owned by the current user.
        oDataList = arcpy.ListTables('*.' + userName + '.*') + arcpy.ListFeatureClasses('*.' + userName + '.*') + arcpy.ListRasters('*.' + userName + '.*')
        
        # Next, for feature datasets owned by the current user
        # get all of the feature classes and add them to the master list.
        for dataset in arcpy.ListDatasets('*.' + userName + '.*'):
            oDataList += arcpy.ListFeatureClasses(feature_dataset=dataset)
        
        # Rebuild indexes and analyze the data owner tables
        arcpy.RebuildIndexes_management(workspace, "NO_SYSTEM", oDataList, "ALL")
        
        arcpy.AnalyzeDatasets_management(workspace, "NO_SYSTEM", oDataList, "ANALYZE_BASE", "ANALYZE_DELTA", "ANALYZE_ARCHIVE")
        
        '''
        *************************
        End Data Owner(s) Section
        *************************
        '''
        
        # set the workspace back to the geodatabase administrator workspace
        workspace = 'Database Connections/admin.sde'
        
        # Get a list of all the replica versions in the geodatabase
        replicaVersions = [replica.version for replica in arcpy.da.ListReplicas(workspace)]
        
        '''
        - We now have a list of versions that were created by taking a map offline (verReconcileList)
        - We also have a list of replica versions (replicaVersions)
        - The versions that we were reconciling are ready to be deleted if they are not currently pointing to a version
        - We are going to loop through the reconcile versions list and remove any versions that are still pointing to a replica
        - The versions remaining in the reconcile list are ready to be cleaned (deleted) up because there are no maps/replicas pointing to them. 
        '''
        
        # Use the list of versions associated with users/maps that we reconciled earlier. Remove any versions from the list that are still being used by a replica. 
        for replicaVer in replicaVersions:
            if replicaVer in verReconcileList:
                verReconcileList.remove(replicaVer)
        
        # Loop through the versionsList and delete versions that are no longer being referenced by a replica. 
        # Since these versions are no longer being referenced by a replica, we can assume it's safe to delete them.
        if len(verReconcileList) > 0:     #check to see that the list is not empty
            for version in verReconcileList:
                try:
                    arcpy.DeleteVersion_management(workspace, version)
                except:
                    print("Failed to delete version.")
                    print(arcpy.GetMessages(2))
        else:
            print("No versions to delete.")
    
    else:
        print("No versions to reconcile, aborting version maintenance routine.")

except:
    print(arcpy.GetMessages(2))
    
print("Done.")

ArcGIS Desktop

  • Inicio
  • Documentación
  • Soporte

ArcGIS

  • ArcGIS Online
  • ArcGIS Desktop
  • ArcGIS Enterprise
  • ArcGIS
  • ArcGIS Developer
  • ArcGIS Solutions
  • ArcGIS Marketplace

Acerca de Esri

  • Quiénes somos
  • Empleo
  • Blog de Esri
  • Conferencia de usuarios
  • Cumbre de desarrolladores
Esri
Díganos su opinión.
Copyright © 2021 Esri. | Privacidad | Legal