我正在用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"`
}
我的脚本的代码在这里:
https://gist.github.com/hectorgool/c9e18d7d6324a9ed1a2df92ddcc95c08#file-elastigo_example-go-L80
最佳答案
那不是编译错误,您得到panic: runtime error: index out of range
如果 slice searchresponse.Hits.Hits
的长度为0,则索引第一个元素将超出范围且发生恐慌。您可以先使用searchresponse.Hits.Len()
检查点击数。
关于elasticsearch - go + elastigo紧急:运行时错误:索引超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36344680/