在Golang中使用Elasticsearch scriptfield

时间:2018-05-01 11:46:15

标签: elasticsearch go

我尝试使用scriptfield来计算DocumentResponse结构中的小计(小时*价格)。没有scriptfield就可以正常工作。

所有这些都基于此示例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"`
}

这是我尝试搜索并返回包含scriptfield的结构的地方:

    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

1 个答案:

答案 0 :(得分:0)

在做unmarshal之前,请检查hit.Source,因为我可以看到你正在取消引用hit.Source,试试这个并告诉我它是否能解决问题

for _, hit := range result.Hits.Hits {
        var doc DocumentResponse
        if hit.Source !=nil{
            err:=json.Unmarshal(*hit.Source, &doc)
            if err!=nil{
                fmt.Printf("error unmarshal the doc ,error %+v",err)
                continue
            }
            docs = append(docs, doc)
        }
    }