Elastigo和Go,使用带有变量的Raw json字符串进行搜索

This site have an example of elasticsearch query in go:

https://github.com/mattbaird/elastigo

The example is this:

A search using raw json string

searchJson := `{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}`
out, err := core.SearchRequest(true, "twitter", "tweet", searchJson, "")
if len(out.Hits.Hits) == 1 {
  fmt.Println(string(out.Hits.Hits[0].Source))
}

But i need something like this:

A varible inside a raw json string

term := "my search term"

searchJson := `{
        "size" : "size",
        "query" : {
            "match" : {
                "_all" : {
                    "query" : term,
                    "operator" : "and"  
                }
            }
        },
        "sort" : [{
            "name" : { 
                "order" : "asc", 
                "mode" : "avg" 
            }
        }]
    }`

How can i put a varible term inside a raw json string?

Is posible put a varible inside a raw json string?

You can use templates to fill in that value:

term := "\"my search term\""

searchJSONTmpl := `{
        "size" : "size",
        "query" : {
            "match" : {
                "_all" : {
                    "query" : {{.Term}},
                    "operator" : "and"  
                }
            }
        },
        "sort" : [{
            "name" : { 
                "order" : "asc", 
                "mode" : "avg" 
            }
        }]
    }`

tmpl, err := template.New("blah").Parse(searchJSONTmpl)
if err != nil {
    log.Fatal(err)
}   

data := map[string]string{
    "Term": term,
}   

if err := tmpl.Execute(os.Stdout, data); err != nil {
    log.Fatal(err)
}

If you want to store the new JSON string into a variable, use bytes.Buffer instead of os.Stdout when executing the template.