Skip to content

new Java API client throws org.elasticsearch.client.ResponseException when there is a version conflict #285

Open
@frank-montyne

Description

@frank-montyne

Elasticsearch Version

7.17.3

Installed Plugins

No response

Java Version

bundled

OS Version

macOS Montery

Problem Description

When adding 2 documents with the same id to an index I get a org.elasticsearch.client.ResponseException instead of the new co.elastic.clients.elasticsearch._types.ElasticsearchException. That is very confusing when working with the new Java AOI client. Seems like a bug.

Example code:

private boolean addLock(Lock distributedLock) throws Exception {
		try {
			// A version conflict status exception will be thrown if the document already exists for the same id.
			if (logger.isDebugEnabled()) logger.debug(String.format("Adding distributed lock %s -> %s", getThreadInfo(), distributedLock.toJson()));
			
			elasticSearch.getESClient().index(builder -> 
				builder
					.index(lockIndex)
					.id(distributedLock.id())
					.withJson(distributedLock.toESJsonReader())
					.opType(OpType.Create)
					.waitForActiveShards(asBuilder -> asBuilder.count(1))
					.refresh(Refresh.True));
			
			if (logger.isDebugEnabled()) logger.debug(String.format("Distributed lock added %s -> %s", getThreadInfo(), distributedLock.toJson()));
			return true;
		}
		// Seems like a bug in ElasticSearch to throw an org.elasticsearch.client.ResponseException instead of the new co.elastic.clients.elasticsearch._types.ElasticsearchException!
		// Catching both for the moment being.
		catch (ResponseException e) {
			// Only version conflict exceptions are allowed.
			if (e.getResponse().getStatusLine().getStatusCode() != RestStatus.CONFLICT.getStatus()) throw e;
			
			// ElasticSearch version conflict. Another host/process/thread already performed an action on this lock.
			if (logger.isDebugEnabled()) logger.debug(String.format("Failed to add distributed lock. ES version conflict %s -> %s", getThreadInfo(), distributedLock.toJson()));
			return false;
		}
		catch (ElasticsearchException e) {
			// Only version conflict exceptions are allowed.
			if (e.response().status() != RestStatus.CONFLICT.getStatus()) throw e;
			
			// ElasticSearch version conflict. Another host/process/thread already performed an action on this lock.
			if (logger.isDebugEnabled()) logger.debug(String.format("Failed to add distributed lock. ES version conflict %s -> %s", getThreadInfo(), distributedLock.toJson()));
			return false;
		}
	}

Steps to Reproduce

Add 2 document with the same id

Logs (if relevant)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions