卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35698本站已运行399

使用 olivere/elastic elasticsearch go 库时如何调试/查看生成的查询?

使用 olivere/elastic elasticsearch go 库时如何调试/查看生成的查询?

使用olivere/elastic elasticsearch go库时,调试和查看生成的查询是一个非常重要的步骤。在开发过程中,我们经常需要确保我们构建的查询是正确的,并且能够返回我们期望的结果。php小编新一将为您介绍一些方法来调试和查看生成的查询,以确保您的代码能够正常工作。无论是在开发环境还是生产环境中,这些技巧将帮助您更好地理解和调试您的代码。

问题内容

我试图找出 https://github.com/olivere/elastic 库生成的查询是什么,就像发送到 elasticsearch 服务器的实际 json 值查询一样。

有一些关于跟踪日志的文档(我使用的如下所示),但这似乎不包括查询。

client, err := elastic.NewClient(
...
elastic.SetTraceLog(log.New(os.Stdout,"",0)),
)

我似乎也无法在此处的文档中找到任何相关内容:https://pkg.go.dev/github.com/olivere/elastic?utm_source=godoc

解决方法

根据文档,你可以提供自己的http客户端:

// 获取客户端。您还可以在此处提供您自己的 http 客户端。
客户端,err := elastic.newclient(elastic.seterrorlog(errorlog))

好吧,文档到此结束:)...实际上您必须提供 doer 接口。
我实例化了一个实现 doer 接口的结构,并装饰了 http.do() 以记录 http.request 转储:

免责声明: 对于这个问题的范围,这只是我针对在 docker 容器中运行的弹性实例使用的一个最小示例。在生产中,不要运行不安全的 tls,不要对凭据进行硬编码,根据需要配置 http 传输等。

package main

import (
    "context"
    "crypto/tls"
    "fmt"
    "net/http"
    "net/http/httputil"

    "github.com/olivere/elastic/v7"
)

type logginghttpelasticclient struct {
    c http.client
}

func (l logginghttpelasticclient) do(r *http.request) (*http.response, error) {
    // log the http request dump
    requestdump, err := httputil.dumprequest(r, true)
    if err != nil {
        fmt.println(err)
    }
    fmt.println("reqdump: " + string(requestdump))
    return l.c.do(r)
}

func main() {
    doer := logginghttpelasticclient{
        c: http.client{
            // load a trusted ca here, if running in production
            transport: &http.transport{
                tlsclientconfig: &tls.config{insecureskipverify: true},
            },
        },
    }

    client, err := elastic.newclient(
        // provide the logging doer here
        elastic.sethttpclient(doer),

        elastic.setbasicauth("elastic", "<password>"),
        elastic.seturl("https://:9200"),
        elastic.setsniff(false), // this is specific to my docker elastic runtime
    )
    if err != nil {
        panic(err)
    }

    /*
        generate a random http request to check if it's logged
    */
    ac := client.alias()
    ac.add("myindex", "myalias").do(context.background())
}

这是输出:

reqDump: POST /_aliases HTTP/1.1
Host: 127.0.0.1:9200
Accept: application/json
Authorization: Basic base64(<user>:<pass>)
Content-Type: application/json
User-Agent: elastic/7.0.32 (linux-amd64)

{"actions":[{"add":{"alias":"myAlias","index":"myIndex"}}]}

我假设也可以使用 settracelog,但我选择了已知路径。

卓越飞翔博客
上一篇: 在测试 Go 时如何跨包共享设置和拆卸方法?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏