Created
August 14, 2013 14:24
-
-
Save chritchens/6231540 to your computer and use it in GitHub Desktop.
Just a simple example on using elastigo, a Go driver for Elasticsearch. It's also an occasion to play with the encode/json package. In this case the docs are Couchbase documents indexed by Elasticsearch through the official river plugin. The type of the docs, `couchbaseDocuments`, is automatically set by the plugin. Plugin page: http://www.couch…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "log" | |
import "encoding/json" | |
import "time" | |
import "github.com/mattbaird/elastigo/api" | |
import "github.com/mattbaird/elastigo/core" | |
type Person struct { | |
Name string `json:name` | |
Surname string `json:surname` | |
Gender string `json:gender` | |
Birthday time.Time `json:birthday` | |
Location Geopoint | |
} | |
type Geopoint struct { | |
Lat float64 `json:lat` | |
Lon float64 `json:lon` | |
} | |
func main() { | |
api.Domain = "localhost" | |
// search females | |
var searchQuery = `{ | |
"query": { | |
"term": {"sex":"female"} | |
} | |
}` | |
response, err := core.SearchRequest(true, "people", "couchbaseDocument", searchQuery, "", 0) | |
if err != nil { | |
log.Fatalf("The search of females has failed:", err) | |
} | |
var values []interface{} | |
for _, v := range response.Hits.Hits { | |
var value map[string]interface{} | |
err := json.Unmarshal(v.Source, &value) | |
if err != nil { | |
log.Fatalf("Failed to unmarshal, line 43", err) | |
} | |
values = append(values, value) | |
} | |
fmt.Println(values) | |
// search males | |
searchQuery = `{ | |
"query": { | |
"term": {"sex":"male"} | |
} | |
}` | |
response2, err := core.SearchRequest(true, "people", "couchbaseDocument", searchQuery, "", 0) | |
if err != nil { | |
log.Fatalf("The search of males has failed:", err) | |
} | |
var values2 []interface{} | |
for _, v := range response2.Hits.Hits { | |
var value2 map[string]interface{} | |
err := json.Unmarshal(v.Source, &value2) | |
if err != nil { | |
log.Fatalf("Failed to unmarshal, line 65", err) | |
} | |
values2 = append(values2, value2) | |
} | |
fmt.Println(values2) | |
jsonV2, err := json.Marshal(values2) | |
if err != nil { | |
log.Fatalf("Failed marshalling: line 71", err) | |
} | |
fmt.Println(string(jsonV2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment