CRUD operations
This page covers common CRUD (Create, Read, Update, Delete) operations with the Go client using the typed API and the esdsl builders. For the low-level equivalents, see the low-level API.
import "github.com/elastic/go-elasticsearch/v9/typedapi/esdsl"
For this example, let's create an index named test-index and provide a mapping for the field price which will be an integer.
The esdsl mapping builders provide a fluent syntax for defining index mappings. The correct type field is set automatically for each property:
res, err := es.Indices.Create("test-index").
Mappings(
esdsl.NewTypeMapping().
AddProperty("price", esdsl.NewIntegerNumberProperty()),
).
Do(context.Background())
- The name of the index to create.
- Start a mapping builder with
NewTypeMapping(). - Chain
AddProperty()calls to define each field.
The standard way of indexing a document is to provide the document body to the index request. The document will be serialized as JSON and sent to Elasticsearch.
document := struct {
Id int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
}{
Id: 1,
Name: "Foo",
Price: 10,
}
res, err := es.Index("index_name").
Id("1").
Document(document).
Do(context.Background())
- The target index name.
- Optionally set the document ID.
- Pass the struct directly; serialization is handled automatically.
Alternatively, you can use the Raw method and provide already serialized JSON:
res, err := es.Index("index_name").
Raw([]byte(`{
"id": 1,
"name": "Foo",
"price": 10
}`)).Do(context.Background())
Retrieving a document follows the API as part of the argument of the endpoint. You provide the index and the id, then run the query.
res, err := es.Get(
"index_name",
"doc_id",
).Do(context.Background())
- The index to retrieve the document from.
- The document ID.
If you do not wish to retrieve the content of the document and want only to check if it exists in your index, use the IsSuccess shortcut:
if exists, err := es.Exists("index_name", "doc_id").IsSuccess(nil); exists {
// The document exists!
} else if err != nil {
// Handle error.
}
Result is true if everything succeeds, false if the document doesn't exist. If an error occurs during the request, you will get false and the relevant error.