【问题标题】:Searching Elasticsearch with Golang使用 Golang 搜索 Elasticsearch
【发布时间】:2017-04-06 01:31:12
【问题描述】:

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

【问题讨论】:

  • 获取请求通常不会提交数据。 Post 和 Put 请求可以。 stackoverflow.com/questions/8498371/curl-get-and-x-get
  • 尽管发送带有 GET 请求的正文并不常见,但它是完全有效的,并且没有理由不这样做。如果您只读取数据而不更改/添加数据,则 GET 是正确的选择,而 POST 将是错误的。 Elastic 使用 GET 进行查询,对于更复杂的查询,它使用 GET 请求正文中的数据。
  • 如果您查看对 http.Get 的调用,它有一个参数,即 URL。在您的非工作示例中,您没有传递有效的 URL;您正在传递您将传递给 curl 的内容,这不是一回事。 URL 没有像 -d 这样的标志。

标签: curl elasticsearch go get


【解决方案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))

}

【讨论】:

  • reticentroot,感谢您的帮助,此解决方案也可以正常工作。
  • @FrankJ 没问题,很乐意提供帮助。
【解决方案2】:

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

【讨论】:

猜你喜欢
  • 2023-01-17
  • 2018-07-24
  • 2011-12-08
  • 1970-01-01
  • 2023-01-24
  • 2015-05-23
  • 2015-09-04
  • 2012-09-15
  • 1970-01-01
相关资源
最近更新 更多