Перестройка индексов в системных таблицах базы геоданных с помощью скрипта Python

Эта тема относится только к ArcGIS for Desktop Standard и ArcGIS for Desktop Advanced.

Индексы в базе данных используются для быстрого нахождения строк, удовлетворяющих фильтру предиката запроса. У большинства системных таблиц базы геоданных есть индексы. Но в версионной многопользовательской базе геоданных есть таблицы, которые изменяются с наибольшей частотой. Для таких таблиц требуется наиболее частая перестройка индекса. Это следующие системные таблицы: states, state_lineages и mv_tables_modified. При больших объемах редактирования версионной базы геоданных, индексы этих таблиц следует обновлять каждые сутки.

Администратор базы геоданных может создать автономный Python-скрипт, который будет вызывать инструмент Перестроить индексы (Rebuild Indexes), и может установить расписание, по которому скрипт будет запускаться и перестраивать индексы таких таблиц базы геоданных в IBM DB2, Microsoft SQL Server, Oracle или PostgreSQL.

Для запуска скрипта необходимо подключиться к базе геоданных с правами доступа администратора базы геоданных. Существует два способа: создать файл подключения (.sde) и установить указать этот файл в скрипте, или непосредственно в скрипте ввести инструкцию для подключения. Далее, установите расписание для запуска скрипта с помощью компонента операционной системы Windows Назначенные задания или с помощью демон-планировщика задач cron системы Linux.

Шаги:
  1. Скопируйте один из следующих скриптов на компьютер, где установлены Python и один из следующих клиентов ArcGIS:
    • ArcGIS for Desktop (Standard или Advanced лицензии)
    • Ядро базы геоданных ArcGIS Engine с дополнительным модулем Geodatabase Update
    • ArcGIS времени выполнения
    • ArcGIS for Server (Стандартная или Расширенная версия)

    Измените скрипты, внеся в них информацию о вашем сайте.

    В данном скрипте для подключения к базе данных и для запуска скрипта используется существующий файл подключения к базе данных на локальной машине:

    # Name: RSysIdx.py
    # Description: Rebuilds indexes on the states, state_lineages, 
    # and mv_tables_modified tables in an enterprise geodatabase 
    # using an existing .sde file.
    
    # Author: Esri
    
    # Import system modules
    import arcpy, os
    
    # set workspace
    workspace = arcpy.GetParameterAsText(0)
    default_gdb = "C:\\Documents and Settings\<user>\Application Data\ESRI\ArcCatalog\sp_data.sde"
    # set the workspace environment
    arcpy.env.workspace = workspace
    
    # Execute rebuild indexes
    # Note: To use the "SYSTEM" option the workspace user must be an administrator.
    arcpy.RebuildIndexes_management(workspace, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    

    В приведенном образце скрипта содержится информация, необходимая для подключения к базе данных Oracle, для обновления индексов системных таблиц states, state_lineages и mv_tables_modified:

    # Name: RSysIdxOracle.py
    # Description: Rebuilds indexes on the states, state_lineages,
    # and mv_tables_modified tables in an enterprise geodatabase
    # in Oracle.
    
    # Author: Esri
    
    # Import system modules
    import sys
    import arcpy
    import os
    
    # Provide connection information
    server = servername
    service = "5151 | sde:oracle:sid"
    account_authentication = OPERATING_SYSTEM_AUTH | DATABASE_AUTH
    #Leave username and password blank if using OPERATING_SYSTEM_AUTH
    username = gdb_admin_user_name
    password = gdb_admin_password
    version = sde.DEFAULT
    
    
    # Set local variables
    if os.name.lower() == "nt":
       slashsyntax = "\\"
       if os.environ.get("TEMP") == None:
          temp = "c:\\temp"
       else:
          temp = os.environ.get("TEMP")
    else:
       slashsyntax = "/"
       if os.environ.get("TMP") == None:
          temp = "/usr/tmp"
       else:
          temp = os.environ.get("TMP")
    
    Connection_File_Name = temp + slashsyntax + "connection.sde"
    
    # Check for the .sde file and delete it if present
    if os.path.exists(Connection_File_Name):
       os.remove(Connection_File_Name)
    
    #Variable defined within the script; other variable options commented out at the end of the line
    saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
    saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
    
    print "Creating ArcSDE Connection File..."
    # Create ArcSDE Connection File
    # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password
    arcpy.CreateArcSDEConnectionFile_management(temp, "connection.sde", server, service, account_authentication, username, password, saveUserInfo, version, saveVersionInfo)
    
    # Rebuild indexes on system tables
    arcpy.RebuildIndexes_management(Connection_File_Name, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    

    В приведенном образце скрипта содержатся инструкции для подключения авторизованного dbo-пользователя операционной системы к SQL Server и обновления индексов системных таблиц sde_states, sde_state_lineages и sde_mv_tables_modified:

    # Name: RSysIdxSqlServer.py
    # Description: Rebuilds indexes on the sde_states, sde_state_lineages,
    # and sde_mv_tables_modified tables in an enterprise geodatabase
    # in SQL Server.
    
    # Author: Esri
    
    # Import system modules
    import sys
    import arcpy
    import os
    
    # Provide connection information
    server = servername
    service = "5151 | sde:sqlserver:sqlserver_instance"
    database = database_name
    account_authentication = OPERATING_SYSTEM_AUTH | DATABASE_AUTH
    #Leave username and password blank if using OPERATING_SYSTEM_AUTH
    username = gdb_admin_user_name
    password = gdb_admin_password
    version = sde.DEFAULT
    
    
    # Set local variables
    if os.name.lower() == "nt":
       slashsyntax = "\\"
       if os.environ.get("TEMP") == None:
          temp = "c:\\temp"
       else:
          temp = os.environ.get("TEMP")
    else:
       slashsyntax = "/"
       if os.environ.get("TMP") == None:
          temp = "/usr/tmp"
       else:
          temp = os.environ.get("TMP")
    
    Connection_File_Name = temp + slashsyntax + "connection.sde"
    
    # Check for the .sde file and delete it if present
    if os.path.exists(Connection_File_Name):
       os.remove(Connection_File_Name)
    
    #Variable defined within the script; other variable options commented out at the end of the line
    saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
    saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
    
    print "Creating ArcSDE Connection File..."
    # Create ArcSDE Connection File
    # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password
    arcpy.CreateArcSDEConnectionFile_management(temp, "connection.sde", server, service, database, account_authentication, username, password, saveUserInfo, version, saveVersionInfo)
    
    # Rebuild indexes on system tables
    arcpy.RebuildIndexes_management(Connection_File_Name, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    

    В следующем примере sde-пользователь подключается к базе данных PostgreSQL:

    # Name: RSysIdxpg.py
    # Description: Rebuilds indexes on the sde_states, sde_state_lineages,
    # and sde_mv_tables_modified tables in an enterprise geodatabase
    # in PostgreSQL.
    
    # Author: Esri
    
    # Import system modules
    import sys
    import arcpy
    import os
    
    # Provide connection information
    server = servername
    service = "5151 | sde:postgresql:servername"
    database = database_name
    account_authentication = DATABASE_AUTH
    username = gdb_admin_user_name
    password = gdb_admin_password
    version = sde.DEFAULT
    
    
    # Set local variables
    if os.name.lower() == "nt":
       slashsyntax = "\\"
       if os.environ.get("TEMP") == None:
          temp = "c:\\temp"
       else:
          temp = os.environ.get("TEMP")
    else:
       slashsyntax = "/"
       if os.environ.get("TMP") == None:
          temp = "/usr/tmp"
       else:
          temp = os.environ.get("TMP")
    
    Connection_File_Name = temp + slashsyntax + "connection.sde"
    
    # Check for the .sde file and delete it if present
    if os.path.exists(Connection_File_Name):
       os.remove(Connection_File_Name)
    
    #Variable defined within the script; other variable options commented out at the end of the line
    saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
    saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
    
    print "Creating ArcSDE Connection File..."
    # Create ArcSDE Connection File
    # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password
    arcpy.CreateArcSDEConnectionFile_management(temp, "connection.sde", server, service, database, account_authentication, username, password, saveUserInfo, version, saveVersionInfo)
    
    # Rebuild indexes on system tables
    arcpy.RebuildIndexes_management(Connection_File_Name, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    

    В следующем примере sde-пользователь подключается к базе данных DB2:

    # Name: RSysIdxDb2.py
    # Description: Rebuilds indexes on the states, state_lineages,
    # and mv_tables_modified tables in an enterprise geodatabase
    # in DB2.
    
    # Author: Esri
    
    # Import system modules
    import sys
    import arcpy
    import os
    
    # Provide connection information
    server = servername
    service = "5151 | sde:db2"
    database = db_alias
    account_authentication = OPERATING_SYSTEM_AUTH | DATABASE_AUTH
    #Leave username and password blank if using OPERATING_SYSTEM_AUTH
    username = gdb_admin_user_name
    password = gdb_admin_password
    version = sde.DEFAULT
    
    
    # Set local variables
    if os.name.lower() == "nt":
       slashsyntax = "\\"
       if os.environ.get("TEMP") == None:
          temp = "c:\\temp"
       else:
          temp = os.environ.get("TEMP")
    else:
       slashsyntax = "/"
       if os.environ.get("TMP") == None:
          temp = "/usr/tmp"
       else:
          temp = os.environ.get("TMP")
    
    Connection_File_Name = temp + slashsyntax + "connection.sde"
    
    # Check for the .sde file and delete it if present
    if os.path.exists(Connection_File_Name):
       os.remove(Connection_File_Name)
    
    #Variable defined within the script; other variable options commented out at the end of the line
    saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
    saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
    
    print "Creating ArcSDE Connection File..."
    # Create ArcSDE Connection File
    # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password
    arcpy.CreateArcSDEConnectionFile_management(temp, "connection.sde", server, service, database, account_authentication, username, password, saveUserInfo, version, saveVersionInfo)
    
    # Rebuild indexes on system tables
    arcpy.RebuildIndexes_management(Connection_File_Name, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    

    В следующем примере sde-пользователь подключается к базе данных Informix:

    # Name: RSysIdxIDS.py
    # Description: Rebuilds indexes on the states, state_lineages,
    # and mv_tables_modified tables in an enterprise geodatabase
    # in Informix IDS.
    
    # Author: Esri
    
    # Import system modules
    import sys
    import arcpy
    import os
    
    # Provide connection information
    server = servername
    service = "5151 | sde:informix"
    database = odbc_dsn
    account_authentication = OPERATING_SYSTEM_AUTH | DATABASE_AUTH
    #Leave username and password blank if using OPERATING_SYSTEM_AUTH
    username = gdb_admin_user_name
    password = gdb_admin_password
    version = sde.DEFAULT
    
    
    # Set local variables
    if os.name.lower() == "nt":
       slashsyntax = "\\"
       if os.environ.get("TEMP") == None:
          temp = "c:\\temp"
       else:
          temp = os.environ.get("TEMP")
    else:
       slashsyntax = "/"
       if os.environ.get("TMP") == None:
          temp = "/usr/tmp"
       else:
          temp = os.environ.get("TMP")
    
    Connection_File_Name = temp + slashsyntax + "connection.sde"
    
    # Check for the .sde file and delete it if present
    if os.path.exists(Connection_File_Name):
       os.remove(Connection_File_Name)
    
    #Variable defined within the script; other variable options commented out at the end of the line
    saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
    saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
    
    print "Creating ArcSDE Connection File..."
    # Create ArcSDE Connection File
    # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password
    arcpy.CreateArcSDEConnectionFile_management(temp, "connection.sde", server, service, database, account_authentication, username, password, saveUserInfo, version, saveVersionInfo)
    
    # Rebuild indexes on system tables
    arcpy.RebuildIndexes_management(Connection_File_Name, "SYSTEM", "", "ALL")
    print 'Rebuild Complete'
    
  2. После занесения в скрипт информации о подключении, запланируйте запуск скрипта в определенный час в ночное время.
    • В Windows откройте утилиту Назначенные задания из Панели управления и используйте мастер для добавления запланированного задания. На запрос указать программу, которую нужно запускать, укажите свой скрипт Python.
    • В Linux создайте текстовый файл cron, в котором указывается день и время, в которые необходимо запускать скрипт, затем загрузите файл в cron с помощью программы crontab.

      Например, для запуска скрипта Python (с именем rsysidxdb2.py) каждую среду в 22:00 необходимо ввести следующую информацию:

      0 22 * * 3 /usr/bin/rsysidxdb2.py

      Для получения сведений по использованию cron, см. справочные страницы Linux, поставляемые вместе с операционной системой.
9/10/2013