数据推送 Demo

主要是在程序中动态将对应的文档数据封装到Map对象中,再将这些Map对象通过add方法添加到缓存中,最后调用pushDocuments方法,批量提交这些Map对象文档数据。

代码示例

package main

import (
	"fmt"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	ha3engine "github.com/aliyun/alibabacloud-ha3-go-sdk/client"
)

func main() {
	// 创建请求客户端实例
	config := &ha3engine.Config{
		// API域名,可在实例详情页>API入口 查看
		Endpoint: tea.String("ha-cn-i7*****605.public.ha.aliyuncs.com"),
		// 用户名,可在实例详情页>API入口 查看
		AccessUserName: tea.String("username"),
		// 密码,可在实例详情页>API入口 修改
		AccessPassWord: tea.String("password"),
	}

	// 初始化一个client, 用以发送请求.
	client, _clientErr := ha3engine.NewClient(config)

	// 如用户请求时间较长. 可通过此配置增加请求等待时间. 单位 ms
	runtime := &util.RuntimeOptions{
		ConnectTimeout: tea.Int(5000),
		ReadTimeout:    tea.Int(10000),
		Autoretry:      tea.Bool(false),
		IgnoreSSL:      tea.Bool(false),
		MaxIdleConns:   tea.Int(50),
	}
	client.RuntimeOptions = runtime

	// 如果 NewClient 过程中出现异常. 则 返回 _clientErr 且输出 错误信息.
	if _clientErr != nil {
		fmt.Println(_clientErr)
		return
	}

	docPush(client)
}

func docPush(client *ha3engine.Client) {
	pushDocumentsRequestModel := &ha3engine.PushDocumentsRequestModel{}
	// 文档推送的表名称
	tableName := "<table_name>"
	// 文档推送的文档主键字段
	keyField := "<field_pk>"

	array := []map[string]interface{}{}
	filed := map[string]interface{}{
		"fields": map[string]interface{}{
			"id": 1,
			"title":  "测试",
		},
		"cmd": tea.String("add"),
	}
	array = append(array, filed)
	pushDocumentsRequestModel.SetBody(array)

	// 发送请求的方法调用.
	response, _requestErr := client.PushDocuments(tea.String(tableName), tea.String(keyField), pushDocumentsRequestModel)
	// 推送数据时,默认校验是否存在主键字段。如需关闭校验,请设置请求头 X-Opensearch-Validate-Data: false
	//headers := map[string]*string{}
	//headers["X-Opensearch-Validate-Data"] = tea.String("false")
	//pushDocumentsRequestModel.SetHeaders(headers)
	
	// 如果 发送请求 过程中出现异常. 则 返回 _requestErr 且输出 错误信息.
	if _requestErr != nil {
		fmt.Println(_requestErr)
		return
	}

	// 输出正常返回的 response 内容.
	fmt.Println(response)
}