使用 Golang 搜索 Elasticsearch



我对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?

你可以尝试这样的事情。您提交 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))
}

要将正文数据传递给 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。要求更好。

最新更新