Examplesedit

This sections lists a series of frequent use cases that will help you start with this new API.

This is a work in progress, the documentation will evolve in the future.

Creating an indexedit

For this example on how to create an index, lets create an index named test-index and provide a mapping for the field price which will be an integer. Notice how using the builder for the IntegerNumberProperty will automatically apply the correct value for the type field.

res, err := es.Indices.Create("test-index").
    Request(&create.Request{
        Mappings: &types.TypeMapping{
            Properties: map[types.PropertyName]types.PropertyBuilder{
                "price": types.NewIntegerNumberPropertyBuilder().Build(),
            },
        },
    }).
    Do(nil)

Indexing a documentedit

The standard way of indexing a document is to provide a struct to the Request method, the standard json/encoder will be run on your structure and the result will be 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").
    Request(document).
    Do(context.Background())

Alternatively, you can use the Raw method and provide the already serialized JSON:

res, err := es.Index("index_name").
			Raw([]byte(`{
			  "id": 1,
			  "name": "Foo",
			  "price": 10
			}`)).Do(context.Background())

Retrieving a documentedit

Retrieving a document follows the API as part of the argument of the endpoint. In order you provide the index, the id and then run the query:

res, err := es.Get("index_name", "doc_id").Do(context.Background())

Checking for a document existenceedit

If you do not wish to retrieve the content of the document and want only to check if it exists in your index, we provide 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 be granted with a false and the relevant error.

Searchedit

Building a search query can be done with structs or builder. As an example, let’s search for a document with a field name with a value of Foo in the index named index_name.

With a struct request:

res, err := es.Search().
    Index("index_name"). 
    Request(&search.Request{ 
        Query: &types.QueryContainer{
            Match: map[types.Field]types.MatchQuery{
                "name": {Query: "Foo"}, 
            },
        },
    }).Do(context.Background()) 

The targeted index for this search.

The request part of the search.

Match query specifies that name should match Foo.

The query is run with a context.Background and returns the response.

The same query using the builder:

res, err := es.Search().
	Index("index_name").
	Request(search.NewRequestBuilder().
		Query(types.NewQueryContainerBuilder().
			Match(map[types.Field]types.MatchQueryBuilder{
				"name": types.NewMatchQueryBuilder().
					Query("Foo"),
			})).
		Build(),
	).Do(context.Background())

Both of the examples produce the following JSON:

{
  "query": {
    "match": {
      "name": {
        "query": "Foo"
      }
    }
  }
}

Aggregationsedit

Given documents with a price field, we run a sum aggregation on index_name:

totalPricesAgg, err := es.Search().
	Index("index_name"). 
	Request(
		search.NewRequestBuilder().
			Size(0). 
			Aggregations(
				map[string]*types.AggregationContainerBuilder{
					"total_prices": types.NewAggregationContainerBuilder(). 
						Sum(types.NewSumAggregationBuilder().Field("price")), 
				}).
			Build(),
	).Do(context.Background())

Specifies the index name.

Sets the size to 0 to retrieve only the result of the aggregation.

Specifies the field name on which the sum aggregation runs.

The SumAggregation is part of the AggregationContainer map.