| endpoint | create |
|---|---|
| lang | ruby |
| es_version | 9.3 |
| client | elasticsearch==9.3.0 |
Use client.create to index a document only if it does not already
exist. This guarantees no accidental overwrites.
response = client.create(
index: 'products',
id: 'prod-1',
body: {
name: 'Espresso Machine Pro',
brand: 'BrewMaster',
price: 899.99,
category: 'appliances',
in_stock: true,
rating: 4.7
}
)
puts "#{response['result']} document #{response['_id']}"Unlike index, this will never replace an existing document.
If a document with the same id already exists, an exception with
status 409 is raised:
begin
client.create(index: 'products', id: 'prod-1', body: { name: 'Duplicate' })
rescue Elastic::Transport::Transport::Errors::Conflict
puts 'Document prod-1 already exists'
endOmit the id parameter to let Elasticsearch assign a unique ID:
response = client.index(
index: 'products',
body: { name: 'New Product', price: 49.99 },
op_type: 'create'
)
puts "Created with ID: #{response['_id']}"