首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在go-elasticsearch中使用杜松子酒?

如何在go-elasticsearch中使用杜松子酒?
EN

Stack Overflow用户
提问于 2020-11-28 12:15:52
回答 1查看 467关注 0票数 0

使用gin进行接口。

它的route.go

代码语言:javascript
复制
func Init(api *gin.Engine) {
    r := api.Group("/v1")
    r.GET("/sites/search/:url", site.Search)
}

在控制器文件中,希望使用go-elasticsearch来搜索ES数据。

代码语言:javascript
复制
import (
    "context"
    "github.com/myapp/common/elasticsearch"
)

func Search(ctx *gin.Context) {
   var data bool
   data = GetES(ctx.Request.Context()) 
}

func GetES(ctx context.Context) bool {
    var (
        r   map[string]interface{}
        buf bytes.Buffer
    )

    var buf bytes.Buffer
    query := map[string]interface{}{
        "query": map[string]interface{}{
            "match": map[string]interface{}{
                "title": "test",
            },
        },
    }
    if err := json.NewEncoder(&buf).Encode(query); err != nil {
        log.Fatalf("Error encoding query: %s", err)
    }


    res, err := elasticsearch.ESClient.Search(
        elasticsearch.ESClient.Search.WithContext(ctx),
        elasticsearch.ESClient.Search.WithIndex("indexname"),
        elasticsearch.ESClient.Search.WithBody(&buf),
        elasticsearch.ESClient.Search.WithTrackTotalHits(true),
    )
    // ...
}

当前go-elasticsearch的初始化方法是在一个公共文件中使用ctx context.Context

代码语言:javascript
复制
import (
    "context"
    elasticsearch "github.com/elastic/go-elasticsearch/v8"
    "github.com/elastic/go-elasticsearch/v8/esapi"
)

func Init(ctx context.Context) {
    var (
        ESClient = *elasticsearch.Client
    )
    // ...
    res, err := esapi.InfoRequest{}.Do(ctx, ESClient)
    // ...
}

如果在控制器Search函数中使用req *http.Request,则可以成功调用数据。但是gin的ctx *gin.Context会导致错误:

代码语言:javascript
复制
runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:199 (0x44470b)
    panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:394 (0x444548)
    sigpanic: panicmem()
/application/site/controller.go:100 (0xe9afea)
    GetES: elasticsearch.ESClient.Search.WithContext(ctx),
/application/site/controller.go:77 (0xe9a8a4)
    Search: data = GetES(ctx.Request.Context())
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/auth/authenticate.go:16 (0xb90f7a)
    APIKeyAuthenticate.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/error/error_handler.go:13 (0xb3c60e)
    Handle500.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/error/error_handler.go:27 (0xb3c84f)
    Handle400.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/recovery.go:83 (0x99bad3)
    RecoveryWithWriter.func1: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/logger.go:241 (0x99ac00)
    LoggerWithConfig.func1: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
    (*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:409 (0x991f1c)
    (*Engine).handleHTTPRequest: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:367 (0x99161d)
    (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2802 (0x6dc303)
    serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1890 (0x6d7ba4)
    (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1357 (0x45d300)
    goexit: BYTE    $0x90   // NOP

我还尝试在GetES函数中使用ctx *gin.Context

代码语言:javascript
复制
func GetES(ctx *gin.Context) bool {

或者在ES的搜索方法中设置context.Background()

代码语言:javascript
复制
elasticsearch.ESClient.Search.WithContext(context.Background()),

仍然收到错误。

如何将gingo-elasticsearch与合适的Context类型一起使用?

这个方法需要什么内容?

https://github.com/elastic/go-elasticsearch/blob/master/_examples/main.go#L127

EN

回答 1

Stack Overflow用户

发布于 2020-12-31 14:42:17

*gin.Contextgo-elasticsearch询问的上下文不同,如果你在*gin.Context中有搜索词,你可以使用像search()这样的函数来获取和查询它们。

代码语言:javascript
复制
 package main
    
    import (
        "bytes"
        "context"
        "encoding/json"
        es "github.com/elastic/go-elasticsearch"
        api "github.com/elastic/go-elasticsearch/esapi"
        app "github.com/gin-gonic/gin"
        "io/ioutil"
        "log"
        "net/http"
        "strings"
    )
    
    var c *es.Client
    
    func init() {
        // connect to elastic search client
        cf := es.Config{
            Addresses: []string{
                "http://localhost:9200",
            },
        }
        e, err := es.NewClient(cf)
        if err != nil {
            log.Println(err)
        }
        c = e
        // make a new index
        // put some new data
        // search database for data
    }
    
    
    
    func search(term string, key string) (by []byte, err error) {
        q := map[string]interface{}{
            "query": map[string]interface{}{
                "match": map[string]interface{}{
                    key: term},
            },
        }
        var bts bytes.Buffer
        if err = json.NewEncoder(&bts).Encode(q); err != nil {
            return
        }
        r, err := c.Search(
            c.Search.WithContext(context.Background()),
            c.Search.WithIndex("test"),
            c.Search.WithBody(&bts),
            c.Search.WithTrackTotalHits(true),
            c.Search.WithPretty(),
        )
        if err != nil {
            return
        }
        defer r.Body.Close()
        by, err = ioutil.ReadAll(r.Body)
        if err != nil || r.StatusCode != http.StatusOK {
            return
        }
        return
    }
    
    func handlerr(a interface{}, err error) {
        if err != nil {
            log.Println(err)
        }
        log.Printf("%s", a)
    }
    func main() {
        r:=app.Default()
        r.GET("/",GetES)
        r.Run(":8080")
        return
    }
      
    
     func GetES(c *gin.Context){
       res, err := search("my experiments with truth", "title")
       handlerr(res,err)
       c.JSON{http.StatusOK,res}
       return
     }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65046350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档