有没有类似于Golang的Scan()方法(用于SQL)的方法可以用于Elasticsearch?

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

Is there any method similar to Golang's Scan() method (used for SQL) for Elasticsearch?

问题

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

我对Go和ES都不熟悉。我想将以下代码片段转换为类似于以下Elasticsearch查询的代码:

query = `SELECT roll_no, name, school FROM students where roll_no = $1`
err = db.QueryRowContext(ctx, query, roll_no).Scan(&Student.ID, &Student.Name, &Student.School)

转换为:

str := fmt.Sprintf(`{"query": { "match": { "roll_no" : %d } } }`, roll_no)
b := []byte(str)
// 调用 retrieve 方法,如下所示

我正在使用HTTP调用连接到ES,但以下代码在解析时显示http: panic serving [::1]:5574: EOF错误。

func retrieve(url string, b []byte) ([]byte, error) {
	request, _ := http.NewRequest("GET", url, bytes.NewBuffer(b))
	request.Header.Set("Content-Type", "application/json; charset=UTF-8")

	client := &http.Client{}
	response, error := client.Do(request)
	if error != nil {
		panic(error)
	}
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)

	s := Student{}
	error = json.NewDecoder(response.Body).Decode(&s)
	if error != nil {
		panic(error)
	}
	fmt.Printf("Student: %v", s)

	return body, error
}

有没有办法通过解析将其存储到一个对象中?

英文:

I am new to both Go and ES. I want to convert the following piece of code:

query = `SELECT roll_no, name, school FROM students where roll_no = $1`
err = db.QueryRowContext(ctx, query, roll_no).Scan(&Student.ID, &Student.Name, &Student.School)

into something like the following Elasticsearch query:

str = fmt.Sprintf(`{"query": { "match": {	"roll_no" : %d  } } }`, roll_no)
b := []byte(str)
// calls retrieve method, which is shown below

I am connecting to ES using HTTP calls, but the following code is showing http: panic serving [::1]:5574: EOF error while parsing.

func retrieve(url string, b []byte) ([]byte, error) {
	request, _ := http.NewRequest("GET", url, bytes.NewBuffer(b))
	request.Header.Set("Content-Type", "application/json; charset=UTF-8")

	client := &http.Client{}
	response, error := client.Do(request)
	if error != nil {
		panic(error)
	}
	defer response.Body.Close()
    body, _ := ioutil.ReadAll(response.Body)

	s := Student{}
	error = json.NewDecoder(response.Body).Decode(&s)
	if error != nil {
		panic(error)
	}
	fmt.Printf("Student: %v", s)

	return body, error
}

Is there anyway I can store it into an object by parsing?

答案1

得分: 1

你可以使用Golang的Scan()方法(通常用于SQL)在Elasticsearch中吗?

完全不行。

database/sql包需要一个数据库驱动程序,而Elasticsearch没有提供这样的驱动程序。

英文:

> How can I use Golang's Scan() method (normally used for SQL) in Elasticsearch?

Not at all.

Package database/sql needs a database driver and there isn't one for ES.

huangapple
  • 本文由 发表于 2021年8月17日 18:51:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68816010.html
匿名

发表评论

匿名网友

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

确定