使用Golang搜索Elasticsearch

时间:2017-04-06 01:31:13

标签: curl elasticsearch go get

我对Go来说相对较新,我目前正尝试在弹性搜索中搜索记录,下面是我创建的基本代码,到目前为止,我能够执行简单的GET请求" http://10.132.0.13:9200/"并按预期返回结果。但是,一旦我尝试运行稍微复杂的GET请求,它就会失败。

以下是我到目前为止创建的代码。

package main

import (
 "fmt"

 "io/ioutil"
 "net/http"
)

func main() {

 //request, err := http.Get(`http://10.132.0.13:9200/`) // this just returns the test page

 request, err := http.Get(`http://10.132.0.13:9200/database-*/_search?pretty -d { "query": { "match": {"_all": "searchterm"}}}`)

 if err != nil {
  //error
 }
 defer request.Body.Close()

 body, err := ioutil.ReadAll(request.Body)

 fmt.Println(string(body))

}

我可以使用curl -xget直接查询索引,并返回预期的结果

有没有办法在golang中实现类似的curl -xget?

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情。您提交的JSON数据(或表单数据),这意味着您应该使用POST或PUT。 XGET会覆盖GET请求的默认行为。使用curl切换到POST并查看您的查询是否仍然有效。

package main

import (
    "bytes"
    "fmt"

    "io/ioutil"
    "net/http"
)

func main() {
    query := []byte(`{"query": { "match": {"_all": "searchterm"}}}`)
    req, err := http.NewRequest("POST", "http://10.132.0.13:9200/database-*/_search?pretty", bytes.NewBuffer(query))
    if err != nil {
        panic(err)
    }
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(body))

}

答案 1 :(得分:1)

要将正文数据传递给get请求,您必须以不同的方式构造请求对象:

requestBody := `{ "query": { "match": {"_all": "searchterm"}}}`
// convert string to reader
requestReader := bytes.NewReader([]byte(requestBody))
// construct the request object
request, err := http.NewRequest("GET", `http://10.132.0.13:9200/database-*/_search?pretty`, requestReader)
// send the request using default client
response, err := http.DefaultClient.Do(request)

if err != nil {
    panic(err)
}
defer response.Body.Close()

body, err := ioutil.ReadAll(response.Body)

fmt.Println(string(body))

如果你必须使用更复杂的弹性查询,那么使用go客户端可能是有意义的,例如:http://olivere.github.io/elastic/

但是根据你的用例,使用http.Request更好。