【笔记】Go语言操作Elasticsearch数据库

前言

Go语言操作Elasticsearch数据库

下载依赖

1
go get github.com/olivere/elastic/v7

引入依赖

1
import "github.com/olivere/elastic/v7"

建立连接

elastic.SetURL("http://127.0.0.1:9200"):定义Elasticsearch的URL
elastic.SetSniff(false):如果是单实例,禁用集群嗅探

1
client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"), elastic.SetSniff(false))

Ping探测

1
client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"), elastic.SetSniff(false))

对索引的操作

查询索引是否存在

<index_name>:索引名

1
exist, err := client.IndexExists("<index_name>").Do(context)

新增索引

1
2
3
4
5
6
7
8
9
10
11
mapping = `
{
"mappings": {
"properties": {
"name": {"type": "keyword"}
}
}
}
`

res, err := client.CreateIndex("<index_name>").BodyString(mapping).Do(context)

删除索引

1
res, err := client.DeleteIndex("<index_name>").Do(context)

对文档的操作

新增文档

user:用于新增的结构体变量
<id>:文档id,如果不定义则Elasticsearch会为这个文档自动生成id

1
2
3
var user = User{}

res, err := client.Index().Index(configMap["es.db"]).Id("<id>").BodyJson(user).Do(context)

删除文档

1
res, err := client.Delete().Index("<index_name>").Id("<id>").Do(context)

查询文档

1
res, err := client.Get().Index("<index_name>").Id("<id>").Do(context)

搜索文档

Terms

searchSource:搜索条件

1
2
3
var searchSource *elastic.SearchSource = elastic.NewSearchSource().Query(elastic.NewTermsQuery("content", keywordInterfaceList...))

client.Search().Index("<index_name>").SearchSource(searchSource).Do(context)

完成

参考文献

topgoer的博客
热浪编程的博客
哔哩哔哩——枫枫知道
CSDN——lishuangquan1987