ord_bear
ord_bear

Reputation: 63

How can I put a format specifier in Elasticsearch query using Go?

In the following code, I want to put a variable id, like some format specifier %d. How do I do this for the following elasticsearch query with Golang?

str := `{
        "query": {
          "match": {
            "id": 123
          }
        }
      }`
    
s := []byte(str)
url := "http://localhost:9200/student/_delete_by_query"

_, err = helper.GoDelete(url, s)
if err != nil {
    return err
}
return nil

Upvotes: 3

Views: 143

Answers (2)

aherve
aherve

Reputation: 4070

fmt.Sprintf could work, but is also prone to errors. I would create the appropriate structures, then use json.Marshal to do it:

type (
    Match struct {
        ID int `json:"id"`
    }
    Query struct {
        Match Match `json:"match"`
    }
    MyStruct struct {
        Query Query `json:"query"`
    }
)

func main() {
    s := MyStruct{
        Query: Query{
            Match: Match{
                ID: 123,
            },
        },
    }
    bytes, err := json.Marshal(s)
}

Upvotes: 0

Oleg Butuzov
Oleg Butuzov

Reputation: 5405

Using fmt.Sprintf may be the simplest way to do that, not the fastest. but simplest.

d := 123
id := fmt.Sprintf(`{"query": {"match": {"id": %d}}}`, d)

Upvotes: 1

Related Questions