Я пытаюсь использовать поле сценария для расчета промежуточной суммы (часы * цена) в структуре DocumentResponse. Без скрипта работает нормально.
Все основано на этом примере https://outcrawl.com/go-elastic-search-service/
Не удивляйтесь, если это очень простая ошибка. Я совершенно новичок в кодировании.
Я думаю, что что-то идет не так, когда демаршаллирует ответ.
Это структуры, о которых идет речь:
type DocumentResponse struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Project string `json:"project"`
Hours float64 `json:"hours"`
Date string `json:"date"`
Price float64 `json:"price"`
Vat float64 `json:"vat"`
Subtotal float64 `json:"subtotal"`
}
type SearchResponse struct {
Time string `json:"time"`
Hits string `json:"hits"`
Documents []DocumentResponse `json:"documents"`
}
Здесь я пытаюсь найти и вернуть структуру с включенным полем сценария:
boolQ := elastic.NewMatchAllQuery()
subtotal := elastic.NewScriptField("doc['subtotal'].value", elastic.NewScript("doc['price'].value * doc['hours'].value"))
src := elastic.NewSearchSource().Query(boolQ).ScriptFields(subtotal)
result, err := elasticClient.Search().
Index(elasticIndexName).
SearchSource(src).
From(skip).Size(take).
Do(c.Request.Context())
if err != nil {
log.Println(err)
errorResponse(c, http.StatusInternalServerError, "Something went wrong")
return
}
res := SearchResponse{
Time: fmt.Sprintf("%d", result.TookInMillis),
Hits: fmt.Sprintf("%d", result.Hits.TotalHits),
}
// Transform search results before returning them
docs := make([]DocumentResponse, 0)
for _, hit := range result.Hits.Hits {
var doc DocumentResponse
json.Unmarshal(*hit.Source, &doc)
docs = append(docs, doc)
}
res.Documents = docs
c.JSON(http.StatusOK, res)
}
Запуск примерно так:
curl 'localhost:8080/search?start=2018-04-01&end=2018-04-30&project=bogus'
Ничего не возвращает и выдает ошибку:
2018/05/01 13:20:42 [Recovery] panic recovered:
GET /search?start=2018-04-01&end=2018-04-30&project=bogus HTTP/1.1
Host: localhost:8080
Accept: */*
User-Agent: curl/7.59.0
runtime error: invalid memory address or nil pointer dereference
/usr/lib/go/src/runtime/panic.go:502 (0x42ac98)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d),
uint32(d.siz), uint32(d.siz))
/usr/lib/go/src/runtime/panic.go:63 (0x429d0d)
panicmem: panic(memoryError)
/usr/lib/go/src/runtime/signal_unix.go:388 (0x43fa49)
sigpanic: panicmem()
/home/niklas/go/src/git.enokinetwork.com/niklas/goest/main.go:168
(0x9bf56a)
searchEndpoint: json.Unmarshal(*hit.Source, &doc)
/home/niklas/go/src/github.com/gin-gonic/gin/context.go:110 (0x8ad492)
(*Context).Next: c.handlers[c.index](c)
/home/niklas/go/src/github.com/gin-gonic/gin/recovery.go:46 (0x8bd369)
RecoveryWithWriter.func1: c.Next()
/home/niklas/go/src/github.com/gin-gonic/gin/context.go:110 (0x8ad492)
(*Context).Next: c.handlers[c.index](c)
/home/niklas/go/src/github.com/gin-gonic/gin/logger.go:83 (0x8bc69b)
LoggerWithWriter.func1: c.Next()
/home/niklas/go/src/github.com/gin-gonic/gin/context.go:110 (0x8ad492)
(*Context).Next: c.handlers[c.index](c)
/home/niklas/go/src/github.com/gin-gonic/gin/gin.go:351 (0x8b4854)
(*Engine).handleHTTPRequest: c.Next()
/home/niklas/go/src/github.com/gin-gonic/gin/gin.go:318 (0x8b4092)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/lib/go/src/net/http/server.go:2694 (0x67fc9b)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/lib/go/src/net/http/server.go:1830 (0x67be50)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/lib/go/src/runtime/asm_amd64.s:2361 (0x456e70)
goexit: BYTE $0x90 // NOP