golang常用库之olivere elastic包 | go操作elasticsearch

golang常用库之elastic包 | 操作elasticsearch

olivere/elastic/​​ 这个版本被广泛使用,我们也用这个。

olivere elastic包

官网: https://olivere.github.io/elastic/
github: https://github.com/olivere/elastic

Go的选择很少:最著名的是olivere/elastic ,而官方的则是elastic/go-elasticsearch。
olivere elastic作为golang比较常用的elasticsearch工具包。

Elastic是GO编程语言的Elasticsearch的客户端。自2012年以来,我们在生产中使用它。它支持Elasticsearch版本1.x,2.x,5.x,6.x和7.x。

注意:es版本不同,要导入不同的包。

olivere elastic包 使用

官方文档:https://pkg.go.dev/github.com/olivere/elastic

Go语言操作ElasticSearch(基本操作)
参考URL: https://blog.csdn.net/my_miuye/article/details/110496025
golang操作elasticsearch(oliver/elastic使用文档)
参考URL: https://blog.csdn.net/p1049990866/article/details/117254708
Go操作elasticsearch
参考URL: https://www.putianhui.cn/posts/1e4561eceb2d/
数据操作(3)go操作ElasticSearch
参考URL: https://zhuanlan.zhihu.com/p/347419756

在 Elasticsearch中,索引类似于数据库。 以前,elasticsearch 中有一个叫做 type 的表。 但是由于类型已在当前版本中删除,因此现在只有索引。
我们创建了一个名为 indexName 的索引。在接下的步骤中,我们将想这个索引里写入一些数据,也就是一些文档。
我们现在要做的是用文档填充我们的 Elasticsearch 索引。 如果你不熟悉该定义,请知道它与数据库中的行非常相似。

go 测试demo代码

我们使用第三方库https://github.com/olivere/elastic 来连接ES并进行操作。

官方https://github.com/olivere/elastic ,就有对应 _test.go 测试文件,参考相关代码即可。

如下:测试demo:
json入库es

setup_test.go文件

package es_demo

import (
	"fmt"
	"time"
)

const (
	testIndexName      = "elastic-test"
)

type tweet struct {
    
    
	Uuid     string        `json:"uuid"`
	User     string        `json:"user"`
	Message  string        `json:"message"`
	Retweets int           `json:"retweets"`
	Image    string        `json:"image,omitempty"`
	Created  time.Time     `json:"created,omitempty"`
	Tags     []string      `json:"tags,omitempty"`
	Location string        `json:"location,omitempty"`
}

func (t tweet) String() string {
    
    
	return fmt.Sprintf("tweet{User:%q,Message:%q,Retweets:%d}", t.User, t.Message, t.Retweets)
}

es_test.go

package es_demo

import (
	"context"
	"fmt"
	elastic "github.com/olivere/elastic/v7"
	uuid "github.com/satori/go.uuid"
	"testing"
	"time"
)



func TestIndex(t *testing.T)  {
    
    
	Client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
	fmt.Println(Client, err)

	tweet1 := tweet{
    
    Uuid: uuid.NewV4().String(),User: "olivere", Message: "Welcome to Golang and Elasticsearch.",
		Created: time.Date(2014, 1, 18, 23, 59, 58, 0, time.UTC)}
	// Add a document
	indexResult, err := Client.Index().
		Index(testIndexName).
		//Id("1").
		BodyJson(&tweet1).
		Do(context.TODO())
	if err != nil {
    
    
		t.Fatal(err)
	}
	if indexResult == nil {
    
    
		t.Errorf("expected result to be != nil; got: %v", indexResult)
	}

}

ES基本概念与关系型数据库的比较

在这里插入图片描述以前,elasticsearch 中有一个叫做 type 的表。 但是由于类型已在当前版本中删除,因此现在只有索引。

猜你喜欢

转载自blog.csdn.net/inthat/article/details/126110839