| endpoint | create |
|---|---|
| lang | java |
| es_version | 9.3 |
| client | co.elastic.clients:elasticsearch-java:9.3.0 |
Use client.create() to index a document only if it does not already
exist.
var product = new Product(
"Espresso Machine Pro", "BrewMaster",
899.99, "appliances", true, 4.7
);
var response = client.create(c -> c
.index("products")
.id("prod-1")
.document(product)
);
System.out.println(response.result() + " document " + response.id());Unlike index, this fails if a document with the same ID already
exists.
A version conflict throws an ElasticsearchException with status 409:
try {
client.create(c -> c
.index("products").id("prod-1").document(product));
} catch (ElasticsearchException e) {
if (e.status() == 409) {
System.out.println("Document prod-1 already exists");
} else {
throw e;
}
}Use index with opType(OpType.Create) when you don't need to
specify an ID:
var response = client.index(i -> i
.index("products")
.opType(OpType.Create)
.document(product)
);
System.out.println("Created with ID: " + response.id());