Skip to content

Latest commit

 

History

History
55 lines (45 loc) · 1.15 KB

File metadata and controls

55 lines (45 loc) · 1.15 KB
endpoint create
lang ruby
es_version 9.3
client elasticsearch==9.3.0

Elasticsearch 9.3 create endpoint (Ruby example)

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.

Handling conflicts

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'
end

Auto-generated IDs

Omit 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']}"