Manutenção¶
Resource and analytics tables¶
DHIS2 features a set of generated database tables which are used as a basis for various system functionality. These tables can be executed immediately or scheduled to be executed at regular intervals through the user interface. They can also be generated through the Web API as explained in this section. This task is typically one for a system administrator and not consuming clients.
The resource tables are used internally by the DHIS2 application for various analysis functions. These tables are also valuable for users writing advanced SQL reports. They can be generated with a POST or PUT request to the following URL:
/ api / 33 / resourceTables
The analytics tables are optimized for data aggregation and used currently in DHIS2 for the pivot table module. The analytics tables can be generated with a POST or PUT request to:
/ api / 33 / resourceTables / analytics
| Query parameter | Options | Descrição |
|---|---|---|
| skipResourceTables | false | true | Skip generation of resource tables |
| skipAggregate | false | true | Skip generation of aggregate data and completeness data |
| skipEvents | false | true | Skip generation of event data |
| skipEnrollment | false | true | Skip generation of enrollment data |
| skipOrgUnitOwnership | false | true | Skip generation of organization unit ownership data |
| lastYears | inteiro | Number of last years of data to include |
Note
lastYears=0 means latest or continuous analytics, as defined in Continuous analytics table.
"Data Quality" and "Data Surveillance" can be run through the monitoring task, triggered with the following endpoint:
/ api / 33 / resourceTables / monitoring
This task will analyse your validation rules, find any violations and persist them as validation results.
These requests will return immediately and initiate a server-side process.
Manutenção¶
To perform maintenance you can interact with the maintenance resource. You should use POST or PUT as a method for requests. The following methods are available.
A limpeza das tabelas analíticas eliminará todas as tabelas analíticas.
POST PUT / api / maintenance / analyticsTablesClear
A análise da tabela analítica coleta estatísticas sobre o conteúdo das tabelas analíticas no banco de dados.
POST PUT / api / maintenance / analyticsTablesAnalyze
Expired invitations clear will remove all user account invitations which have expired.
POST PUT / api / maintenance / expiredInvitationsClear
Period pruning will remove periods which are not linked to any data values.
POST PUT / api / maintenance / periodPruning
Zero data value removal will delete zero data values linked to data elements where zero data is defined as not significant:
POST PUT / api / maintenance / zeroDataValueRemoval
A remoção de valores de dados excluídos de forma reversível excluirá permanentemente os valores de dados excluídos de forma reversível.
POST PUT / api / maintenance / softDeletedDataValueRemoval
A remoção de instância de estágio de programa excluída de forma reversível excluirá permanentemente eventos excluídos de forma reversível.
POST PUT / api / maintenance / softDeletedProgramStageInstanceRemoval
A remoção de instância de programa excluída de forma reversível excluirá permanentemente as inscrições excluídas de forma reversível.
POST PUT / api / maintenance / softDeletedProgramInstanceRemoval
A remoção de instâncias de entidades rastreadas excluídas de forma reversível excluirá permanentemente as instâncias de entidades rastreadas excluídas de forma reversível.
POST PUT / api / maintenance / softDeletedTrackedEntityInstanceRemoval
Eliminar visualizações SQL eliminará todas as visualizações SQL do banco de dados. Observe que isso não excluirá as entidades de exibição DHIS2 SQL.
POST PUT / api / maintenance / sqlViewsDrop
Criar visualizações SQL recriará todas as visualizações SQL no banco de dados.
POST PUT / api / maintenance / sqlViewsCreate
A atualização do combo de opção de categoria removerá os combos de opção de categoria em falta para todas as combinações de categoria.
POST PUT / api / maintenance / categoryOptionComboUpdate
Também é possível atualizar combos de opção de categoria para uma única combinação de categoria usando o seguinte endpoint.
POST PUT / api / maintenance / categoryOptionComboUpdate / categoryCombo / <category-combo-uid>
A limpeza do cache irá limpar o cache do aplicativo Hibernate e os caches da partição analítica.
POST PUT / api / maintenance / cacheClear
A atualização dos caminhos da unidade organizacional irá gerar novamente a propriedade do caminho da unidade organizacional. Isso pode ser útil, por exemplo se você importou unidades organizacionais com SQL.
POST PUT / api / maintenance / ouPathsUpdate
A poda de dados removerá registros de conjunto de dados completos, aprovações de dados, auditorias de valor de dados e valores de dados, neste caso para uma unidade de organização.
POST PUT / api / maintenance / dataPruning / organisationUnits / <org-unit-id>
Remoção de dados para elementos de dados, o que removerá auditorias de valor de dados e valores de dados.
POST PUT /api/maintenance/dataPruning/dataElements/<data-element-uid>
A validação de metadados aplicará todas as regras de validação de metadados e retornará o resultado da operação.
POST PUT / api / metadataValidation
O recarregamento de aplicativo atualizará o cache gerenciado DHIS2 dos aplicativos instalados lendo o sistema de arquivos.
POST PUT / api / appReload
As operações de manutenção são suportadas em um estilo de lote com uma solicitação POST para o recurso api / maintenance onde as operações são fornecidas como parâmetros de consulta:
POST PUT / api / maintenance? AnalyticsTablesClear = true & expiredInvitationsClear = true
& periodPruning = true & zeroDataValueRemoval = true & sqlViewsDrop = true & sqlViewsCreate = true
& categoryOptionComboUpdate = true & cacheClear = true & ouPathsUpdate = true
Informação do sistema¶
The system resource provides you with convenient information and functions. The system resource can be found at /api/system.
Gerar identificadores¶
To generate valid, random DHIS2 identifiers you can do a GET request to this resource:
/ api / 33 / sistema / id? limite = 3
The limit query parameter is optional and indicates how many identifiers you want to be returned with the response. The default is to return one identifier. The response will contain a JSON object with an array named codes, similar to this:
{
"codes": [
"Y0moqFplrX4",
"WI0VHXuWQuV",
"BRJNBBpu4ki"
]
}
O formato UID DHIS2 tem estes requisitos:
-
11 caracteres.
-
Alphanumeric characters only, ie. alphabetic or numeric characters (A-Za-z0-9).
-
Comece com um caractere alfabético (A-Za-z).
Ver informações do sistema¶
To get information about the current system you can do a GET request to this URL:
/ api / 33 / system / info
JSON and JSONP response formats are supported. The system info response currently includes the below properties.
{
"contextPath": "http://yourdomain.com",
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/29.0.1547.62",
"calendar": "iso8601",
"dateFormat": "yyyy-mm-dd",
"serverDate": "2021-01-05T09:16:03.548",
"serverTimeZoneId": "Etc/UTC",
"serverTimeZoneDisplayName": "Coordinated Universal Time",
"version": "2.13-SNAPSHOT",
"revision": "11852",
"buildTime": "2013-09-01T21:36:21.000+0000",
"serverDate": "2013-09-02T12:35:54.311+0000",
"environmentVariable": "DHIS2_HOME",
"javaVersion": "1.7.0_06",
"javaVendor": "Oracle Corporation",
"javaIoTmpDir": "/tmp",
"javaOpts": "-Xms600m -Xmx1500m -XX:PermSize=400m -XX:MaxPermSize=500m",
"osName": "Linux",
"osArchitecture": "amd64",
"osVersion": "3.2.0-52-generic",
"externalDirectory": "/home/dhis/config/dhis2",
"databaseInfo": {
"type": "PostgreSQL",
"name": "dhis2",
"user": "dhis",
"spatialSupport": false
},
"memoryInfo": "Mem Total in JVM: 848 Free in JVM: 581 Max Limit: 1333",
"cpuCores": 8
}
Note
If the user requesting this resource does not have full authority then only properties which are not considered sensitive will be included.
To get information about the system context only, i.e. contextPath and userAgent, you can make a GET request to the below URL. JSON and JSONP response formats are supported:
/ api / 33 / system / context
Verifique se a combinação de nome de usuário e senha está correta¶
To check if some user credentials (a username and password combination) is correct you can make a GET request to the following resource using basic authentication:
/ api / 33 / sistema / ping
You can detect the outcome of the authentication by inspecting the HTTP status code of the response header. The meanings of the possible status codes are listed below. Note that this applies to Web API requests in general.
| HTTP Status code | Descrição | Outcome |
|---|---|---|
| 200 | OK | Authentication was successful |
| 302 | Found | No credentials were supplied with the request - no authentication took place |
| 401 | Unauthorized | The username and password combination was incorrect - authentication failed |
Ver o status da tarefa assíncrona¶
Tasks which often take a long time to complete can be performed asynchronously. After initiating an async task you can poll the status through the system/tasks resource by supplying the task category and the task identifier of interest.
When polling for the task status you need to authenticate as the same user which initiated the task. The following task categories are supported:
| Identifier | Descrição |
|---|---|
| ANALYTICS_TABLE | Generation of the analytics tables. |
| RESOURCE_TABLE | Generation of the resource tables. |
| MONITORING | Processing of data surveillance/monitoring validation rules. |
| DATAVALUE_IMPORT | Import of data values. |
| EVENT_IMPORT | Import of events. |
| ENROLLMENT_IMPORT | Import of enrollments. |
| TEI_IMPORT | Import of tracked entity instances. |
| METADATA_IMPORT | Import of metadata. |
| DATA_INTEGRITY | Processing of data integrity checks. |
Each asynchronous task is automatically assigned an identifier which can be used to monitor the status of the task. This task identifier is returned by the API when you initiate an async task through the various async-enabled endpoints.
Monitorando uma tarefa¶
You can poll the task status through a GET request to the system tasks resource like this:
/ api / 33 / system / tasks / {task-category-id} / {task-id}
Um exemplo de solicitação pode ter a seguinte aparência:
/ api / 33 / sistema / tarefas / DATAVALUE_IMPORT / j8Ki6TgreFw
The response will provide information about the status, such as the notification level, category, time and status. The completed property indicates whether the process is considered to be complete.
[{
"uid": "hpiaeMy7wFX",
"level": "INFO",
"category": "DATAVALUE_IMPORT",
"time": "2015-09-02T07:43:14.595+0000",
"message": "Import done",
"completed": true
}]
Monitorando todas as tarefas de uma categoria¶
You can poll all tasks for a specific category through a GET request to the system tasks resource:
/ api / 33 / system / tasks / {task-category-id}
An example request to poll for the status of data value import tasks looks like this:
/ api / 33 / sistema / tarefas / DATAVALUE_IMPORT
Monitore todas as tarefas¶
You can request a list of all currently running tasks in the system with a GET request to the system tasks resource:
/ api / 33 / sistema / tarefas
A resposta será semelhante a esta:
[{
"EVENT_IMPORT": {},
"DATA_STATISTICS": {},
"RESOURCE_TABLE": {},
"FILE_RESOURCE_CLEANUP": {},
"METADATA_IMPORT": {},
"CREDENTIALS_EXPIRY_ALERT": {},
"SMS_SEND": {},
"MOCK": {},
"ANALYTICSTABLE_UPDATE": {},
"COMPLETE_DATA_SET_REGISTRATION_IMPORT": {},
"DATAVALUE_IMPORT": {},
"DATA_SET_NOTIFICATION": {},
"DATA_INTEGRITY": {
"OB1qGRlCzap": [{
"uid": "LdHQK0PXZyF",
"level": "INFO",
"category": "DATA_INTEGRITY",
"time": "2018-03-26T15:02:32.171",
"message": "Data integrity checks completed in 38.31 seconds.",
"completed": true
}]
},
"PUSH_ANALYSIS": {},
"MONITORING": {},
"VALIDATION_RESULTS_NOTIFICATION": {},
"REMOVE_EXPIRED_RESERVED_VALUES": {},
"DATA_SYNC": {},
"SEND_SCHEDULED_MESSAGE": {},
"DATAVALUE_IMPORT_INTERNAL": {},
"PROGRAM_NOTIFICATIONS": {},
"META_DATA_SYNC": {},
"ANALYTICS_TABLE": {},
"PREDICTOR": {}
}]
Ver resumos de tarefas assíncronas¶
The task summaries resource allows you to retrieve a summary of an asynchronous task invocation. You need to specify the category and optionally the identifier of the task. The task identifier can be retrieved from the response of the API request which initiated the asynchronous task.
Para recuperar o resumo de uma tarefa específica, você pode emitir uma solicitação para:
/ api / 33 / system / taskSummaries / {task-category-id} / {task-id}
Um exemplo de solicitação pode ser assim:
/ api / 33 / system / taskSummaries / DATAVALUE_IMPORT / k72jHfF13J1
A resposta será semelhante a esta:
{
"responseType": "ImportSummary",
"status": "SUCCESS",
"importOptions": {
"idSchemes": {},
"dryRun": false,
"async": true,
"importStrategy": "CREATE_AND_UPDATE",
"reportMode": "FULL",
"skipExistingCheck": false,
"sharing": false,
"skipNotifications": false,
"datasetAllowsPeriods": false,
"strictPeriods": false,
"strictCategoryOptionCombos": false,
"strictAttributeOptionCombos": false,
"strictOrganisationUnits": false,
"requireCategoryOptionCombo": false,
"requireAttributeOptionCombo": false,
"skipPatternValidation": false
},
"description": "Import process completed successfully",
"importCount": {
"imported": 0,
"updated": 431,
"ignored": 0,
"deleted": 0
},
"dataSetComplete": "false"
}
You might also retrieve import summaries for multiple tasks of a specific category with a request like this:
/ api / 33 / system / taskSummaries / {task-category-id}
Obtenha informações de aparência¶
You can retrieve the available flag icons in JSON format with a GET request:
/ api / 33 / system / flags
You can retrieve the available UI styles in JSON format with a GET request:
/ api / 33 / system / styles
Cluster info¶
When DHIS 2 is set up in a cluster configuration, it is useful to know which node in the cluster acts as the leader of the cluster. The following API can be used to get the details of the leader node instance. The API supports both JSON and XML formats.
GET /api/36/cluster/leader
A sample JSON response looks like this:
{
"leaderNodeId": "play-dhis2-org-dev",
"leaderNodeUuid": "d386e46b-26d4-4937-915c-025eb99c8cad",
"currentNodeId": "play-dhis2-org-dev",
"currentNodeUuid": "d386e46b-26d4-4937-915c-025eb99c8cad",
"leader": true
}
Elementos de dados mínimo-máximo¶
The min-max data elements resource allows you to set minimum and maximum value ranges for data elements. It is unique by the combination of organisation unit, data element and category option combo.
/ api / minMaxDataElements
| Item | Descrição | Tipo de dados |
|---|---|---|
| source | Organisation unit identifier | Corda |
| dataElement | Data element identifier | Corda |
| optionCombo | Data element category option combo identifier | Corda |
| min | Minimum value | Inteiro |
| max | Maximum value | Inteiro |
| generated | Indicates whether this object is generated by the system (and not set manually). | Boolean |
You can retrieve a list of all min-max data elements from the following resource:
GET /api/minMaxDataElements.json
Você pode filtrar a resposta assim:
GET /api/minMaxDataElements.json?filter=dataElement.id:eq:UOlfIjgN8X6
GET /api/minMaxDataElements.json?filter=dataElement.id:in:[UOlfIjgN8X6,xc8gmAKfO95]
The filter parameter for min-max data elements supports two operators: eq and in. You can also use the fields query parameter.
GET /api/minMaxDataElements.json?fields=:all,dataElement[id,name]
Add/update single min-max data element¶
Para adicionar um novo elemento de dados mín-máx, use a solicitação POST para:
POST /api/minMaxDataElements.json
O formato de conteúdo JSON é semelhante a este:
{
"min": 1,
"generated": false,
"max": 100,
"dataElement": {
"id": "UOlfIjgN8X6"
},
"source": {
"id": "DiszpKrYNg8"
},
"optionCombo": {
"id": "psbwp3CQEhs"
}
}
If the combination of data element, organisation unit and category option combo exists, the min-max value will be updated.
Delete single min-max data element¶
Para excluir um elemento de dados mín-máx, envie uma solicitação com o método DELETE:
DELETE /api/minMaxDataElements.json
O conteúdo JSON está em formato semelhante ao acima:
{
"min": 1,
"generated": false,
"max": 100,
"dataElement": {
"id": "UOlfIjgN8X6"
},
"source": {
"id": "DiszpKrYNg8"
},
"optionCombo": {
"id": "psbwp3CQEhs"
}
}
Add/update multiple min-max data elements¶
To add or update multiple min-max data elements, you can use a POST request to the following resource:
POST /api/minMaxDataElements/upsert
The JSON content format for multiple min-max data elements looks like this:
[
{
"dataSet": "BfMAe6Itzgt",
"values": [
{
"dataElement": "s46m5MS0hxu",
"orgUnit": "Qc9lf4VM9bD",
"optionCombo": "Prlt0C1RF0s",
"minValue": 27,
"maxValue": 564
},
{
"dataElement": "s46m5MS0hxu",
"orgUnit": "Qc9lf4VM9bD",
"optionCombo": "V6L425pT3A0",
"minValue": 0,
"maxValue": 100
}
]
Note that the dataSet property is required in the request body when using JSON. Each min-max value should contain UID references to dataElement, orgUnit, optionCombo. The minValue and maxValue properties represent the minimum and maximum values for the data element, respectively and will be parsed as integers.
You can also specify the generated property if you want to indicate whether the min-max data element is generated by the system or set manually. If not specified, it defaults to true.
Gzipped JSON payloads are also supported for this endpoint, which can be useful for large datasets. The server will automatically decompress the gzipped content. If you send a gzipped payload, make sure to set the Content-Encoding header to gzip and include the Content-Type header with the value application/json. The payload itself should be part of the request body.
CSV payloads are also supported for this endpoint. The CSV file should be delimited with commas. You should set the Content-Type header to text/csv and the Accept header to application/json. You will also need to specify the dataSet query parameter in the request URL. The CSV payload should contain the following columns:
| Column Name | Descrição |
|---|---|
| dataElement | The UID of the data element |
| orgUnit | The UID of the organisation unit |
| optionCombo | The UID of the category option combo |
| minValue | The minimum value for the data element |
| maxValue | The maximum value for the data element |
| generated | (optional) Indicates whether the min-max data element is generated by the system or set manually. Defaults to true if not specified. |
An example CSV payload might look like this:
dataElement,orgUnit,optionCombo,minValue,maxValue,generated
s46m5MS0hxu,Qc9lf4VM9bD,Prlt0C1RF0s,27,564,false
s46m5MS0hxu,Qc9lf4VM9bD,V6L425pT3A0,0,100,true
Delete multiple min-max data elements¶
To delete multiple min-max data elements, you can use a DELETE request to the following resource:
DELETE /api/minMaxDataElements/delete
The JSON content for the request body should be in the same format as for adding or updating multiple min-max data elements, but you only need to specify the dataElement, orgUnit, and optionCombo properties for each min-max data element you want to delete. The minValue, maxValue, and generated properties are not required for deletion. Gzipped JSON payloads and CSV payloads are also supported for this endpoint, similar to the add/update multiple min-max data elements endpoint. Be sure to set the appropriate headers (Content-Encoding as gzip and Content-Type as application/csv or application/json) when sending the request. If using CSV, you will also need to specify the dataSet query parameter in the request URL.
Exceções de bloqueio¶
The lock exceptions resource allows you to open otherwise locked data sets for data entry for a specific data set, period and organisation unit. You can read lock exceptions from the following resource:
/ api / lockExceptions
To create a new lock exception you can use a POST request and specify the data set, period and organisation unit:
POST / api / lockExceptions? Ds = BfMAe6Itzgt & pe = 201709 & ou = DiszpKrYNg8
To delete a lock exception you can use a similar request syntax with a DELETE request:
DELETE / api / lockExceptions? Ds = BfMAe6Itzgt & pe = 201709 & ou = DiszpKrYNg8
Data summary¶
The data summary resource provides some metrics about the database and level of system usage. The metrics include: Data statistics can be accessed with a GET request to :
GET /api/dataSummary
A JSON response similar to the one below is provided. We will explain the various parts of the response in the following sections.
Object counts represent the number of different metadata objects in the system. These counts can be useful for monitoring the size and complexity of a DHIS2 instance. An example of the objectCounts part of the response is shown below: Note that these values represent the number of objects at a specific point in time and will change as data is added or removed from the system.
"objectCounts": {
"indicator": 77,
"trackerevent": 55781,
"trackedEntity": 73125,
"visualization": 292,
"period": 384,
"organisationUnit": 1332,
"validationRule": 37,
"dataValue": 4935894,
"dataElement": 1037,
"program": 14,
"organisationUnitGroup": 18,
"singleevent": 317816,
"enrollment": 73126,
"indicatorType": 5,
"eventVisualization": 50,
"event": 373597,
"indicatorGroup": 17,
"dataSet": 26,
"userGroup": 34,
"user": 131,
"dataElementGroup": 84,
"map": 91,
"dashboard": 27
}
In addition to object counts, the data summary response also includes various usage statistics related to users and data in the form of histograms. activeUsers represents the number of users who have performed an action which results in a data statistics event (opened a dashboard, viewed a report, etc.) over the past hour (0), today (1), last 2 days (2), last 7 days (7) and last 30 days (30). Note that the "today" value represents the number of unique users who have been active since midnight server time, while the "last 2 days", "last 7 days" and "last 30 days" values represent the number of unique users who have been active in the respective time periods calculated backwards from the current time. logins represents the number of successful user logins over the same time periods. userInvitations provides the number of user invitations currently in the system, both total and expired. An example of these parts of the response is shown below:
"activeUsers": {
"0": 1,
"1": 1,
"2": 1,
"7": 2,
"30": 2
},
"logins": {
"0": 1,
"1": 1,
"2": 131,
"7": 131,
"30": 131
},
"userInvitations": {
"all": 0,
"expired": 0
}
In addition, the data summary response includes information about different types of data stored in the system. dataValueCount represents the number of data values entered into the system over the past hour (0), today (1), last 7 days (7) and last 30 days (30). singleEventCount and trackerEventCount represents the number of single events and tracker events entered into the system over the same time periods.
"dataValueCount": {
"0": 0,
"1": 0,
"7": 0,
"30": 0
},
"eventCount": {
"0": 0,
"1": 0,
"7": 1,
"30": 2
}
....
Finally, the data summary response includes information about the system itself, such as the version, revision, build time, system ID and current server date. An example of the system part of the response is shown below:
"system": {
"version": "2.43-SNAPSHOT",
"revision": "db516b5",
"buildTime": "2025-11-18T10:53:50.000",
"systemId": "eed3d451-4ff5-4193-b951-ffcc68954299",
"serverDate": "2025-11-18T10:55:15.048"
}
Data summary Prometheus metrics¶
In order to support the long-term monitoring of DHIS2 instances, a special endpoint is available which outputs the data summary information in the Prometheus text exposition format. This can be fetched from the server by making a GET request to : GET api/dataSummary/metrics
An example of the output is provided below
# HELP data_summary_object_counts Count of metadata objects
# TYPE data_summary_object_counts gauge
data_summary_object_counts{type="indicator"} 77
data_summary_object_counts{type="trackedEntity"} 73125
data_summary_object_counts{type="visualization"} 292
data_summary_object_counts{type="period"} 384
data_summary_object_counts{type="programStageInstance"} 373597
This endpoint provides essentially the same information as the api/dataSummary endpoint, but in a format which Prometheus is capable of scraping and importing. Most of the metrics represent object counts, such as the current number of data elements, organization units, etc.
The build information metric is explained in more detail below.
# HELP data_summary_build_info Build information
# TYPE data_summary_build_info gauge
data_summary_build_info{version="2.42-SNAPSHOT", commit="932e552"} 1737621197
This metric represents the current version and commit hash of the server. The metric itself is an integer and represents the build time as seconds since the epoch. This metric can be easily converted or to an actual date when needed.
Note On systems with large amounts of data, the
dataValueCountandeventCountmetrics may take a long time to compute due to the large number of records in the database. Users should thus use caution if scraping metrics from this endpoint as it may impact the performance of the server. It should generally be sufficient to scrape this endpoint once per day, since this will provide a good overview of the system usage and performance.