GOLANG ES 自定义查询脚本 随机抽取几条数据

环境:golang 1.19 + es7 + olivere

首先是一个寻常的 go 语言查询 ES 的 DDL 语句

esRandRes, _ := core.Es.Search().
			Index("...").
			Query(...).
			From(0).
			Size(20).
			Do(context.Background())

我们只需要加上这句即可

SortBy(elastic.NewScriptSort(elastic.NewScript("Math.random()"),"number"))

比如

esRandRes, _ := core.Es.Search().
			Index("...").
			Query(...).
			SortBy(elastic.NewScriptSort(elastic.NewScript("Math.random()"),"number")).
			From(0).
			Size(20).
			Do(context.Background())

说明:

[ 以下源码均摘自 olivere:sort.go ]

显然,SortBy()函数是用来排序的,他接受一个 Sorter 接口的对象,

Sorter接口 ↓
// Sorter is an interface for sorting strategies, e.g. ScoreSort or FieldSort.
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-sort.html.
type Sorter interface {
	Source() (interface{}, error)
}

然后我们通过 NewScriptSort() 函数创建一个查询脚本

创建脚本的函数 ↓
// NewScriptSort creates and initializes a new ScriptSort.
// You must provide a script and a type, e.g. "string" or "number".
func NewScriptSort(script *Script, typ string) *ScriptSort {
	return &ScriptSort{
		script:    script,
		typ:       typ,
		ascending: true,
	}
}

注意,这个函数有两个参数,第一个参数我们通过 NewScript() 函数创建一个脚本对象,第二个字符串类型的参数如官方注释的第二行所言:

// You must provide a script and a type, e.g. “string” or “number”.
// 你必须提供一个类型,比如 string 或 number

这里我理解是提供第一个 NewScriptSort() 函数参数所写脚本的返回值类型,因为我填 string 是不行的,填了 number 就可以,猜测是对应随机数函数的返回类型。

相对来说,创建脚本的函数就简单多了,就仅仅是:

elastic.NewScript("Math.random()")

第一次使用 golang、olivere 和 ES ,一切都要从头摸索,灵感来自下面这个 java-es 的实现:
https://blog.csdn.net/w1014074794/article/details/120222314

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

控场的朴哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值