使用Golang搜索Elasticsearch

huangapple go评论87阅读模式
英文:

Searching Elasticsearch with Golang

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Go语言还比较新,目前我正在尝试在Elasticsearch中搜索记录,下面是我创建的基本代码,到目前为止,我能够执行简单的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/`) // 这只是返回测试页面

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

    if err != nil {
        // 错误处理
    }
    defer request.Body.Close()

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

    fmt.Println(string(body))

}

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

是否有办法在Go语言中实现类似的curl -xget功能?

英文:

I'm relatively new to Go and I'm currently trying to search records in elastic search, below is the basic code I have created, so far I'm able to perform a simple GET request "http://10.132.0.13:9200/" and results are returned as expected. However, once I try to run a slightly more complex GET request it fails.

Below is the code I have created so far.

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))

}

I can query the index directly with the use of curl -xget and it returns the expected results

Is there a way to implement a similar curl -xget in golang?

答案1

得分: 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))

}

希望对你有帮助!

英文:

You can try something like this. Your submitting JSON data (or form data), which means that you should probably be using a POST or a PUT. XGET overrides the default behavior of a GET request. Using curl switch over to a POST and see if your query still works.

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))

}

答案2

得分: 1

要将请求体数据传递给GET请求,您需要稍微修改请求对象的构造方式:

requestBody := `{ "query": { "match": {"_all": "searchterm"}}}`
// 将字符串转换为Reader
requestReader := bytes.NewReader([]byte(requestBody))
// 构造请求对象
request, err := http.NewRequest("GET", `http://10.132.0.13:9200/database-*/_search?pretty`, requestReader)
// 使用默认客户端发送请求
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))

如果您需要使用更复杂的Elastic查询,可能更合适的是使用Go客户端,例如:http://olivere.github.io/elastic/

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

英文:

To pass body data to a get request you have to construct your request object a bit differently:

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))

If you have to use more complex elastic queries it might make sense to use a go client like for example: http://olivere.github.io/elastic/

But depending on your usecase, using http.Request is better.

huangapple
  • 本文由 发表于 2017年4月6日 09:31:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/43244219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定