Delete old processes of a process definition

With the java API, how it’s possible to delete process instances of a specific process definition if they don’t belong to the last version?

With rest api I can easily achieve that using sort by definitionVersion. With the API I can’t figure how to do it. I don’t have any ordering by Version number.
I’m using camunda 7.8

Hi @Mizar01,

consider the following example:

String processDefinitionId = repositoryService.createProcessDefinitionQuery()
  .processDefinitionVersion(4)
  .singleResult()
  .getId();

HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery()
  .processDefinitionId(processDefinitionId);

historyService.deleteHistoricProcessInstancesAsync(query, "aDeleteReason");
  1. The process definition id with the specific version is retrieved
  2. A historic process instance query is created which filters by #processDefinitionId
  3. With the help of HistoryService#deleteHistoricProcessInstancesAsync historic process instances can be deleted by a query

Does this answer your question?

Cheers,
Tassilo

Not really. I want to delete the processes of the older version of the same definition key, not id.
Your code will delete the instances of the same version(wich I don’t want to).

I solved somehow using the ‘getLatestVersion’ o a definition key and delete all the process instances that does not match the definition id(i.e. the version)

Hi @Mizar01,

could you share your solution? This would help other users if they face the same problem.

Additionally, we created with CAM-9732 a feature request which describes the behavior you are looking for.

Cheers,
Tassilo

Hi tasso94, I thought the same thing, but I was on a trip.

This is the main code for the deletion of the older version instances:

String key = "definitionKeyFoo";
        
ProcessDefinition lastPDef = processEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionKey(key)
            .latestVersion()
            .singleResult();

List<ProcessInstance> lp = pe.getRuntimeService()
            .createProcessInstanceQuery()
            .processDefinitionKey(key)
            .active().list();

for (int j = 0; j < lp.size(); j++) {
        ProcessInstance pi = lp.get(j);
        if (!pi.getProcessDefinitionId().equals(lastPDef.getId())) {
            logger.info("Deleting instance " + pi.getProcessInstanceId() + " as an old version of " + key);
            pe.getRuntimeService().deleteProcessInstance(pi.getProcessInstanceId(), "Deleting old version.");
        }
}