侧边栏壁纸
博主头像
Tony's Blog博主等级

行动起来,coding

  • 累计撰写 83 篇文章
  • 累计创建 58 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
go

elastic.NewTermsQuery踩坑

Tony
2024-02-21 / 0 评论 / 0 点赞 / 12 阅读 / 2595 字

本文链接: https://blog.csdn.net/lishuangquan1987/article/details/130160886

版权

今天发现查询数据查不到,代码片段如下:

objs := make([]interface{}, 0)
	linq.From(batCodes).SelectT(func(i string) interface{} { return i }).ToSlice(&objs)
	searchResult, err := esClient.Search().Size(maxESSize).Index(config.Config.ESConfig.ESIndex).Query(
		elastic.NewBoolQuery().Must(elastic.NewTermsQuery("batcode", objs...)).Do(context.Background())
	if err != nil {
		return nil, err
	}

elastic.NewBoolQuery().Must(elastic.NewTermsQuery("batcode", objs...)) 这一句不能直接传切片,后来查询到很多文章反馈此坑。

感谢文章:https://www.cnblogs.com/xdao/p/9262293.html

改进后:

objs := make([]interface{}, 0)
	linq.From(batCodes).SelectT(func(i string) interface{} { return i }).ToSlice(&objs)
	searchResult, err := esClient.Search().Size(maxESSize).Index(config.Config.ESConfig.ESIndex).Query(
		elastic.NewBoolQuery().Must(elastic.NewTermsQuery("batcode", toInterfaceSlice(objs)...))).Do(context.Background())
	if err != nil {
		return nil, err
	}

// ES的坑!
func toInterfaceSlice(slice interface{}) []interface{} {
	s := reflect.ValueOf(slice)
	if s.Kind() != reflect.Slice {
		panic("InterfaceSlice() given a non-slice type")
	}

	ret := make([]interface{}, s.Len())

	for i := 0; i < s.Len(); i++ {
		ret[i] = s.Index(i).Interface()
	}

	return ret
}

0

评论区