我正在使用elasticsearch测试golang
我正在使用该库: https://github.com/mattbaird/elastigo
我的问题是我跑的时候:
go run elastigo_postal_code2.go
编译器显示如下:
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0x893ce0, 0xc82000a150)
/opt/go/src/runtime/panic.go:464 +0x3ff
main.main()
/home/hector/go/elastigo_postal_code2.go:80 +0xa30
exit status 2
我不确定这意味着什么或我如何解决它!
有人可以帮助我并告诉我我做错了
/*
curl -X PUT "http://localhost:9200/mx2/postal_code/1" -d "
{
\"cp\" : \"20000\",
\"colonia\" : \"Zona Centro\",
\"ciudad\" : \"Aguascalientes\",
\"delegacion\" : \"Aguascalientes\",
\"location\": {
\"lat\": \"22.0074\",
\"lon\": \"-102.2837\"
}
}"
curl -X PUT "http://localhost:9200/mx2/postal_code/2" -d "
{
\"cp\" : \"20008\",
\"colonia\" : \"Delegacion de La Secretaria de Comercio y Fomento Industrial\",
\"ciudad\" : \"Aguascalientes\",
\"delegacion\" : \"Aguascalientes\",
\"location\": {
\"lat\": \"22.0074\",
\"lon\": \"-102.2837\"
}
}"
*/
package main
import (
"encoding/json"
"flag"
"log"
elastigo "github.com/mattbaird/elastigo/lib"
)
var (
eshost *string = flag.String("host", "localhost", "Elasticsearch Server Host Address")
)
func main() {
flag.Parse()
log.SetFlags(log.Ltime | log.Lshortfile)
c := elastigo.NewConn()
c.Domain = *eshost
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
searchJson := `{
"size": 10,
"query": {
"match": {
"all": {
"query": "aguascalientes",
"operator": "and"
}
}
},
"sort": [{
"colonia": {
"order": "asc",
"mode": "avg"
}
}]
}`
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
searchresponse, err := c.Search("mx2", "postal_code", nil, searchJson)
if err != nil {
log.Println("error during search:" + err.Error())
log.Fatal(err)
}
// try marshalling to ElasticSearchResponse type
var t ElasticSearchResponse
bytes, err := searchresponse.Hits.Hits[0].Source.MarshalJSON()
if err != nil {
log.Fatalf("err calling marshalJson:%v", err)
}
json.Unmarshal(bytes, &t)
log.Printf("Search Found: %s", t)
c.Flush()
}
func (t *ElasticSearchResponse) String() string {
b, _ := json.Marshal(t)
return string(b)
}
// used in test suite, chosen to be similar to the documentation
type ElasticSearchResponse struct {
Cp string `json:"cp"`
Colonia string `json:"colonia"`
Ciudad string `json:"ciudad"`
Delegacion string `json:"delegacion"`
Location Location `json:"location"`
}
type Location struct {
Lat string `json:"lat"`
Lon string `json:"lon"`
}
我的scritp的代码在这里:
https://gist.github.com/hectorgool/c9e18d7d6324a9ed1a2df92ddcc95c08#file-elastigo_example-go-L80
答案 0 :(得分:0)
这不是编译错误,你得到panic: runtime error: index out of range
如果切片searchresponse.Hits.Hits
的长度为0,则索引第一个元素将超出范围并出现混乱。您可以先使用searchresponse.Hits.Len()
检查点击次数。