英文:
Elastigo and Go, Search Using Raw json String with variables
问题
这个网站上有一个使用Go语言的elasticsearch查询的示例:
https://github.com/mattbaird/elastigo
示例代码如下:
使用原始JSON字符串进行搜索:
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))
}
但是我需要像这样的代码:
在原始JSON字符串中使用变量
term := "my search term"
searchJson := `{
"size" : "size",
"query" : {
"match" : {
"_all" : {
"query" : term,
"operator" : "and"
}
}
},
"sort" : [{
"name" : {
"order" : "asc",
"mode" : "avg"
}
}]
}`
我如何将变量term放入原始JSON字符串中?
是否可以在原始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?
答案1
得分: 2
你可以使用模板来填充该值:
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)
}
如果你想将新的JSON字符串存储到一个变量中,在执行模板时,请使用bytes.Buffer
而不是os.Stdout
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论