search
HomeBackend DevelopmentGolangHow to debug/view generated queries when using olivere/elastic elasticsearch go library?

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

Debugging and viewing the generated queries is a very important step when using the olivere/elastic elasticsearch go library. During development, we often need to ensure that the queries we build are correct and return the results we expect. PHP editor Xinyi will introduce you to some methods to debug and view the generated queries to ensure that your code is working properly. Whether in a development or production environment, these tips will help you better understand and debug your code.

Question content

I'm trying to find out what the query generated by the https://github.com/olivere/elastic library is like the actual json value query sent to the elasticsearch server.

There is some documentation on tracing logs (the one I use is shown below), but this doesn't seem to include queries.

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

I also can't seem to find anything relevant in the documentation here: https://pkg.go.dev/github.com/olivere/elastic?utm_source=godoc

Workaround

According to the documentation, you can provide your own http client:

// Get the client. You can also provide your own http client here.
Client, err := elastic.newclient(elastic.seterrorlog(errorlog))

Okay, that's the end of the documentation :)...actually you have to provide the doer interface.
I instantiated a struct implementing the doer interface and decorated http.do() to log the http.request dump:

Disclaimer: For the scope of this question, this is just a minimal example of what I'm using against an elastic instance running in a docker container. In production, don't run insecure tls, don't hardcode credentials, configure http transport as needed, etc.

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://<address>: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())
}

This is the output:

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"}}]}

I assumed it would also be possible to use settracelog, but I chose a known path.

The above is the detailed content of How to debug/view generated queries when using olivere/elastic elasticsearch go library?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment