This project contains an example that showcases different features from the official Go Client for OpenSearch that you can use as a reference about how to get started with OpenSearch in your Go apps. It is not intended to provide the full spectrum of what the client is capable of—but it certainly puts you on the right track.
You can run this code with an OpenSearch instance running locally, to which you can leverage the Docker Compose code available in the project. Alternatively, you can also run this code with Amazon OpenSearch that can be easily created using the Terraform code also available in the project.
The data model from this project is a collection of movies from the file movies.json. This file will be loaded in memory and made available within the context, which the other functions will work with. Here is an example of a movie:
{
"year": 2012,
"title": "The Avengers",
"info": {
"directors": [
"Joss Whedon"
],
"release_date": "2012-04-11T00:00:00Z",
"rating": 8.2,
"genres": [
"Action",
"Fantasy"
],
"image_url": "http://ia.media-imdb.com/images/M/MV5BMTk2NTI1MTU4N15BMl5BanBnXkFtZTcwODg0OTY0Nw@@._V1_SX400_.jpg",
"plot": "Nick Fury of S.H.I.E.L.D. assembles a team of superhumans to save the planet from Loki and his army.",
"rank": 48,
"running_time_secs": 8580,
"actors": [
"Robert Downey Jr.",
"Chris Evans",
"Scarlett Johansson"
]
}
}
Once the movies are loaded, the code will create a connection with OpenSearch and make this connection available within the context as well.
newClient, err := opensearch.NewClient(opensearch.Config{
Addresses: []string{
opensearchEndpoint,
},
})
if err != nil {
panic(err)
}
All the movies will be indexed in OpenSearch. The example uses the Bulk API to index documents, which is the equivalent to this:
POST _bulk
{ "index" : { "_index" : "movies", "_id" : "1" } }
{ "Year" : "2012", "Title": "The Avengers" }
An example of document lookup is also available. Out of all movies loaded, an ID will be randomly selected, and the document associated with this ID will be looked up. Just like you would do with:
GET movies/_doc/<DOCUMENT_ID>
Obviously, this project couldn't leave behind an example of a search. The implemented search look for all the best action movies from Keanu Reeves from 1995 to 2005. This search is the equivalent to:
GET movies/_search
{
"query": {
"bool": {
"must": {
"match": {
"Actors.en": "keanu reeves"
}
},
"filter": [
{
"term": {
"Genres.keyword": "Action"
}
},
{"range": {
"Rating": {
"gte": 7.0
}
}},
{"range": {
"Year": {
"gte": 1995,
"lte": 2005
}
}}
]
}
}
}
Finally, the project also runs a very interesting aggregation to find out the top five genres and their respective movie counts. Just like you would do with:
GET movies/_search
{
"size": 0,
"aggs": {
"movieCountPerGenre": {
"terms": {
"field": "Genres.keyword",
"size": 5
}
}
}
}
This project is licensed under the Apache 2.0 License.