Skip to content

Latest commit

 

History

History
59 lines (48 loc) · 1.23 KB

File metadata and controls

59 lines (48 loc) · 1.23 KB
endpoint create
lang java
es_version 9.3
client co.elastic.clients:elasticsearch-java:9.3.0

Elasticsearch 9.3 create endpoint (Java example)

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.

Handling conflicts

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;
    }
}

Auto-generated IDs

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());