elasticsearch - 在 Golang 中使用 Elasticsearch scriptfield

标签 elasticsearch go

我正在尝试使用脚本字段来计算 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

最佳答案

在执行解码之前,不要检查 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)
        }
    }

关于elasticsearch - 在 Golang 中使用 Elasticsearch scriptfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115928/

相关文章:

elasticsearch - GCP托管的ES上的日志提取

Azure Blob Go lib使用TokenCredential访问blob api总是返回错误

go - 什么是 cgo 类型,相当于指向结构的 const 指针?

pointers - json.Unmarshal() 接受指向指针的指针

eclipse - 我无法使用goclipse插件进行调试,windows环境

performance - Elasticsearch应该在没有计算相关性的情况下进行查询(_score)

elasticsearch - Elasticsearch自动完成并针对多个术语字段进行搜索

javascript - 通过 Postman 使用 AWS4 签名进行 CRUD 弹性操作

elasticsearch - 如何为我的Lucene查询添加过滤器?

go - 读取一个通用的 yaml 文件