关于解决es创建doc数据时missing field [Type]的问题

关于解决es创建doc数据时missing field [Type]的问题

‎‎2024‎年‎4‎月‎17‎日,‏‎21:36:08

具体报错:missing required fields: [Type]

这是我没有使用gin框架时候的测试代码:

func Create(data *DemoModel) error {
	indexResponse, err := client.Index().Index(data.Index()).BodyJson(data).Do(context.Background())
	if err != nil {
		logrus.Error(err.Error())
		return err
	}
	logrus.Infof("%#v", indexResponse)
	data.ID = indexResponse.Id
	return nil
}

func main() {
	// DemoModel{}.CreateIndex()
	now := time.Now().Format("2006-01-02 15:04:05")
	Create(&DemoModel{
		Title:     "go",
		UserID:    1,
		CreatedAt: now,
	})
}

结果是正确的,并没有报错missing required fields: [Type]

但是当我使用gin框架来创建doc数据时:

func (a ArticleModel) Create() error {
	indexResponse, err := global.ESClient.Index().Index(a.Index()).BodyJson(a).Do(context.Background())
	if err != nil {
		global.Log.Infof("%#v", indexResponse)
		global.Log.Error(err.Error())
		return err
	}
	a.ID = indexResponse.Id
	return nil
}

结果一直报错missing required fields: [Type]

我查找文档说elasticsearch7.x之后是不需要添加type的,缺省type为"_doc"

Option		Required	Default		Type	Description
document-type
required in 6.x	
(none)	
String	
Elasticsearch document type. Not necessary anymore in .elasticsearch-7

当我加上Type("_doc")的参数指定之后,报错消失,并成功创建doc数据

func (a ArticleModel) Create() error {
	indexResponse, err := global.ESClient.Index().Index(a.Index()).Type("_doc").BodyJson(a).Do(context.Background())
	if err != nil {
		global.Log.Infof("%#v", indexResponse)
		global.Log.Error(err.Error())
		return err
	}
	a.ID = indexResponse.Id
	return nil
}

‎2024‎年‎4‎月‎18‎日,‏‎20:21:11

更新:我在import的时候引入的是 "github.com/olivere/elastic/v7"

但是我今天查看源代码的时候发现,它的文件路径是

image-20240418202643296

之后我找到go.mod文件,发现以下内容

github.com/olivere/elastic v6.2.37+incompatible // indirect
github.com/olivere/elastic/v7 v7.0.32 // indirect

在go.sum文件发现

github.com/olivere/elastic v6.2.37+incompatible h1:UfSGJem5czY+x/LqxgeCBgjDn6St+z8OnsCuxwD3L0U=
github.com/olivere/elastic v6.2.37+incompatible/go.mod h1:J+q1zQJTgAz9woqsbVRqGeB5G1iqDKVBWLNSYW8yfJ8=
github.com/olivere/elastic/v7 v7.0.32 h1:R7CXvbu8Eq+WlsLgxmKVKPox0oOwAE/2T9Si5BnvK6E=
github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCzZ8xDOE09a9k=

这些都是v6在前,v7在后,这或许是在我最开始引入的时候先引入了v6版本,后来才改正为v7,但是没有效果

我发现了没有效果的原因:在声明我的全局变量global.ESClient的时候,我是引入的 "github.com/olivere/elastic",

因为v6在前,所以默认引入的是v6

解决方式:

1、删除go.mod和go.sum中的v6版本

2、在所有声明和返回Elastic.Client地方具体引入v7 "github.com/olivere/elastic/v7"

posted @ 2025-04-09 10:42  小依昂阳  阅读(61)  评论(0)    收藏  举报