Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >go操作elasticsearch示例

go操作elasticsearch示例

原创
作者头像
孤烟
发布于 2022-03-19 07:13:16
发布于 2022-03-19 07:13:16
2.2K0
举报
文章被收录于专栏:golang开发笔记golang开发笔记

这里我使用elasticsearch官方给的go语言包([go-elasticsearch](https://github.com/elastic/go-elasticsearch))

go-elasticsearch向前兼容,这意味着客户端支持与更大或同等次要版本的 Elasticsearch 通信。Elasticsearch 语言客户端仅向后兼容默认发行版,不提供任何保证。

- 包:https://github.com/elastic/go-elasticsearch

- Elasticsearch 权威指南:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

### 环境介绍:

版本

Elasticsearch:v7.15

### 安装

go.mod 文件中添加

```

require github.com/elastic/go-elasticsearch/v8 main

```

或者

````

git clone --branch main https://github.com/elastic/go-elasticsearch.git $GOPATH/src/github.com/elastic/go-elasticsearch

````

### 示例:

新建 es.go 存入 es目录

````

package es

import (

"bytes"

"context"

"encoding/json"

"fmt"

"github.com/elastic/go-elasticsearch/v8"

"github.com/elastic/go-elasticsearch/v8/esapi"

"log"

"net/http"

)

var EsClient *elasticsearch.Client

func init() {

cfg := elasticsearch.Config{

Addresses: []string{

"http://localhost:9200",

},

}

var err erro

EsClient, err = elasticsearch.NewClient(cfg)

if err != nil {

log.Fatalln("Failed to connect to es")

}

}

func failOnError(err error, msg string) {

if err != nil {

log.Fatalf("%s: %s", msg, err)

}

}

// idx 为空,默认随机唯一字符串

func Index(index, idx string, doc map[string]interface{}) {

//index:="my_index_name_v1"

res, err := EsClient.Info()

fmt.Println(res, err)

if err != nil {

log.Fatalf("Error getting response: %s", err)

}

var buf bytes.Buffe

//doc := map[string]interface{}{

// "title": "中国",

// "content": "中国早日统一台湾",

// "time": time.Now().Unix(),

// "date": time.Now(),

//}

if err = json.NewEncoder(&buf).Encode(doc); err != nil {

fmt.Println(err, "Error encoding doc")

return

}

res, err = EsClient.Index(

index, // Index name

&buf, // Document body

EsClient.Index.WithDocumentID(idx), // Document ID

// Document ID

EsClient.Index.WithRefresh("true"), // Refresh

)

//res, err = EsClient.Create(index, idx, &buf)

if err != nil {

fmt.Println(err, "Error create response")

}

defer res.Body.Close()

fmt.Println(res.String())

log.Println(res)

}

//struct 类型允许使用更实际的方法,您可以在其中创建一个新结构,将请求配置作为字段,并使用上下文和客户端作为参数调用 Do() 方法:

func IndexEspi(index, idx string, doc map[string]interface{}) {

//index:="my_index_name_v1"

res, err := EsClient.Info()

fmt.Println(res, err)

if err != nil {

log.Fatalf("Error getting response: %s", err)

}

var buf bytes.Buffe

//doc := map[string]interface{}{

// "title": "中国",

// "content": "中国早日统一台湾",

// "time": time.Now().Unix(),

// "date": time.Now(),

//}

if err = json.NewEncoder(&buf).Encode(doc); err != nil {

fmt.Println(err, "Error encoding doc")

return

}

req := esapi.IndexRequest{

Index: index, // Index name

Body: &buf, // Document body

DocumentID: idx, // Document ID

Refresh: "true", // Refresh

}

res, err = req.Do(context.Background(), EsClient)

if err != nil {

log.Fatalf("Error getting response: %s", err)

}

defer res.Body.Close()

fmt.Println(res.String())

log.Println(res)

}

func Search(index string, query map[string]interface{}) {

res, err := EsClient.Info()

if err != nil {

fmt.Println(err, "Error getting response")

}

//fmt.Println(res.String())

// search - highlight

var buf bytes.Buffe

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "title": title,

// },

// },

// "highlight": map[string]interface{}{

// "pre_tags": []string{"<font color='red'>"},

// "post_tags": []string{"</font>"},

// "fields": map[string]interface{}{

// "title": map[string]interface{}{},

// },

// },

//}

if err := json.NewEncoder(&buf).Encode(query); err != nil {

fmt.Println(err, "Error encoding query")

}

// Perform the search request.

res, err = EsClient.Search(

EsClient.Search.WithContext(context.Background()),

EsClient.Search.WithIndex(index),

EsClient.Search.WithBody(&buf),

EsClient.Search.WithTrackTotalHits(true),

EsClient.Search.WithFrom(0),

EsClient.Search.WithSize(10),

EsClient.Search.WithSort("time:desc"),

EsClient.Search.WithPretty(),

)

if err != nil {

fmt.Println(err, "Error getting response")

}

defer res.Body.Close()

fmt.Println(res.String())

}

//删除 index 根据 索引名 id

func Delete(index, idx string) {

//index:="my_index_name_v1"

res, err := EsClient.Info()

fmt.Println(res, err)

if err != nil {

log.Fatalf("Error getting response: %s", err)

}

res, err = EsClient.Delete(

index, // Index name

idx, // Document ID

EsClient.Delete.WithRefresh("true"),

)

if err != nil {

fmt.Println(err, "Error create response")

}

defer res.Body.Close()

fmt.Println(res.String())

log.Println(res)

}

func DeleteByQuery(index []string, query map[string]interface{}) {

res, err := EsClient.Info()

if err != nil {

fmt.Println(err, "Error getting response")

}

//fmt.Println(res.String())

// search - highlight

var buf bytes.Buffe

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "title": title,

// },

// },

// },

//}

if err := json.NewEncoder(&buf).Encode(query); err != nil {

fmt.Println(err, "Error encoding query")

}

// Perform the search request.

res, err = EsClient.DeleteByQuery(

index,

&buf,

)

if err != nil {

fmt.Println(err, "Error getting response")

}

defer res.Body.Close()

fmt.Println(res.String())

}

func SearchEsapiSql(query map[string]interface{}) {

jsonBody, _ := json.Marshal(query)

req := esapi.SQLQueryRequest{Body: bytes.NewReader(jsonBody)}

res, _ := req.Do(context.Background(), EsClient)

defer res.Body.Close()

fmt.Println(res.String())

}

func SearchHttp(method, url string, query map[string]interface{}) {

jsonBody, _ := json.Marshal(query)

req, _ := http.NewRequest(method, url, bytes.NewReader(jsonBody))

req.Header.Add("Content-type", "application/json")

res, err := EsClient.Perform(req)

if err != nil {

return

}

defer res.Body.Close()

buf := new(bytes.Buffer)

buf.ReadFrom(res.Body)

fmt.Println(buf.String())

}

````

新建 main.go

````

package main

import "demo/es"

func main() {

index := "my_index_name_v4"

//创建索引并设置映射

//query := map[string]interface{}{

// "mappings": map[string]interface{}{

// "properties": map[string]interface{}{

// "title": map[string]interface{}{

// "type": "text",

// },

// "content": map[string]interface{}{

// "type": "text",

// },

// "location": map[string]interface{}{

// "type": "geo_point",

// },

// "time": map[string]interface{}{

// "type": "long",

// },

// "date": map[string]interface{}{

// "type": "date",

// },

// "age": map[string]interface{}{

// "type": "keyword",

// },

// },

// },

//}

//url := index

//注意 映射信息不能更新

//es.SearchHttp("PUT", url, query)

//添加或修改文档,没有索引创建

//doc := map[string]interface{}{

// "title": "你好",

// "content": "中国美丽的城市",

// "location": "41.015, -75.011",

// "time": time.Now().Unix(),

// "date": time.Now(),

// "age": 20,

//}

//es.Index(index, "", doc)

//es.IndexEspi(index, "idx5", doc)

//删除索引

//es.Delete(index, "idx3")

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "title": "vvvvv我爱你!!!!",

// },

// },

//}

//indexArr := []string{index}

//es.DeleteByQuery(indexArr, query)

////搜索单个字段

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "title": "我爱你中国",

// },

// },

// "highlight": map[string]interface{}{

// "pre_tags": []string{"<font color='red'>"},

// "post_tags": []string{"</font>"},

// "fields": map[string]interface{}{

// "title": map[string]interface{}{},

// },

// },

//}

//搜索多个字段

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "multi_match": map[string]interface{}{

// "query": "中国",

// "fields": []string{"title", "content"},

// },

// },

// "highlight": map[string]interface{}{

// "pre_tags": []string{"<font color='red'>"},

// "post_tags": []string{"</font>"},

// "fields": map[string]interface{}{

// "title": map[string]interface{}{},

// },

// },

//}

//提高某个字段权重,可以使用 ^ 字符语法为单个字段提升权重,在字段名称的末尾添加 ^boost ,其中 boost 是一个浮点数:

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "multi_match": map[string]interface{}{

// "query": "中国",

// "fields": []string{"title", "content^2"},

// },

// },

// "highlight": map[string]interface{}{

// "pre_tags": []string{"<font color='red'>"},

// "post_tags": []string{"</font>"},

// "fields": map[string]interface{}{

// "title": map[string]interface{}{},

// },

// },

//}

//显示所有的

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match_all": map[string]interface{}{},

// },

//}

//es.Search(index, query)

//地理距离过滤器( geo_distance )以给定位置为圆心画一个圆,来找出那些地理坐标落在其中的文档:

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "bool": map[string]interface{}{

// "must": map[string]interface{}{

// "match_all": map[string]interface{}{}, // 这里不设置其他查询条件,所以匹配全部文档

// },

// "filter": map[string]interface{}{

// "geo_distance": map[string]interface{}{

// "distance": "100km",

// "location": map[string]interface{}{

// "lat": 40.715,

// "lon": -73.988,

// },

// }},

// },

// },

// "sort": map[string]interface{}{ // 设置排序条件

// "_geo_distance": map[string]interface{}{ //_geo_distance代表根据距离排序

// "location": map[string]interface{}{ //根据location存储的经纬度计算距离。

// "lat": 40.715, //当前纬度

// "lon": -73.988, //当前经度

// },

// "order": "asc", // asc 表示升序,desc 表示降序

// }},

//}

//es.Search(index, query)

//精确值查询

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "age": "20",

// },

// },

//}

//es.Search(index, query)

//范围查询

//通过range实现范围查询,类似SQL语句中的>, >=, <, <=表达式。

//gte范围参数 - 等价于>=

//lte范围参数 - 等价于 <=

//范围参数可以只写一个,例如:仅保留 "gte": 10, 则代表 FIELD字段 >= 10

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "range": map[string]interface{}{

// "age": map[string]interface{}{

// "gte": "19",

// "lte": "20",

// },

// },

// },

//}

//es.Search(index, query)

//组合查询 如果需要编写类似SQL的Where语句,组合多个字段的查询条件,可以使用bool语句。

//"must": [], // must条件,类似SQL中的and, 代表必须匹配条件

//"must_not": [], // must_not条件,跟must相反,必须不匹配条件

//"should": [] // should条件,类似SQL中or, 代表匹配其中一个条件

query := map[string]interface{}{

"query": map[string]interface{}{

"bool": map[string]interface{}{

"must": []map[string]interface{}{

{

"match": map[string]interface{}{

"age": "19",

},

},

{

"match": map[string]interface{}{

"title": "中国",

},

},

},

},

},

}

es.Search(index, query)

//使用mysql的方式来请求

//query := map[string]interface{}{

// "query": "select title from " + index + " where title like '%中国%'", //这里使用mysql的方式来请求,非常简单,符合开发习惯,简化es入门门槛,支持order,支持Limit,那么排序和分页就自己写好了

//}

//query := map[string]interface{}{

// "query": "select title from " + index + " where title = '中国'", //这里使用mysql的方式来请求,非常简单,符合开发习惯,简化es入门门槛,支持order,支持Limit,那么排序和分页就自己写好了

//}

//es.SearchEsapiSql(query)

//测试分词

//query := map[string]interface{}{

// "analyzer": "ik_smart", //智能分词用:ik_smart,最大化分词用:ik_max_word

// "text": "中国华人民",

//}

//url := index + "_analyze?pretty=true"

//query := map[string]interface{}{

// "query": map[string]interface{}{

// "match": map[string]interface{}{

// "title": "我爱你中国",

// },

// },

// "highlight": map[string]interface{}{

// "pre_tags": []string{"<font color='red'>"},

// "post_tags": []string{"</font>"},

// "fields": map[string]interface{}{

// "title": map[string]interface{}{},

// },

// },

//}

//url := index + "/_search"

//es.SearchHttp("GET", url, query)

}

````

### 参考资料

https://github.com/elastic/go-elasticsearch

https://www.tizi365.com/archives/590.html

https://www.elastic.co/guide/cn/elasticsearch/guide/current/_creating_an_index.html

## links

- [目录](https://github.com/guyan0319/golang_development_notes/blob/master/zh/preface.md)

- 上一节:

- 下一节:

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Go语言操作Elastic Search v8客户端
在之前的文章(浅谈Elastic Search V8版本的一些重大改进)中我们了解到了Elastic SearchV8版本相较低版本的一些主要变化,那么它在各个编程语言中的API有没有变化?
闫同学
2024/02/16
1K0
万字详解!在 Go 语言中操作 ElasticSearch
在大数据和搜索引擎技术不断进步的今天,ElasticSearch 已成为业界内非常流行的搜索引擎解决方案,被广泛应用于日志分析、全文搜索、数据分析等领域。针对 Go 语言开发者来说,olivere/elastic 是一个非常强大而且易于使用的 ElasticSearch 客户端库,允许开发者在 Go 应用中轻松地操作 ElasticSearch。
南山竹
2024/07/05
7270
万字详解!在 Go 语言中操作 ElasticSearch
Go:如何获取ES数据
沈宥
2024/07/11
3330
Go:如何获取ES数据
中文全文检索技术路线(elasticsearch全文检索、中文分词ik、tika解析文档)
代码在开源仓库3xxxhttps://github.com/3xxx/engineercms
hotqin888
2021/12/06
1.1K0
中文全文检索技术路线(elasticsearch全文检索、中文分词ik、tika解析文档)
【ES三周年】Informer实战之持久化K8s事件至ElasticSearch
在系列文章中详细讲解了Informer的相关知识,本届番外获取K8s的事件,将其存储到Elasticsearch,可以利用inforrmer机制回去到应用的时间进行外部持久化存储,或者进行过滤分类展示,或进行数据应用分析告警等。
KaliArch
2023/02/10
6120
.NET Core中使用NEST简单操作Elasticsearch
C#中访问Elasticsearch主要通过两个包NEST和Elasticsearch.Net,NEST用高级语法糖封装了Elasticsearch.Net可以通过类Linq的方式进行操作,而Elasticsearch.Net相比之下更为原始直接非常自由。
郑子铭
2023/08/29
9490
.NET Core中使用NEST简单操作Elasticsearch
ElasticSearch 6.x 学习笔记:19.搜索高亮
参照官方文档 https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-request-highlighting.html
程裕强
2022/05/06
5710
Elasticsearch上手——Pyt
Elasticsearch客户端列表:https://www.elastic.co/guide/en/elasticsearch/client/index.html Python API:https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/index.html 参考文档:http://elasticsearch-py.readthedocs.io/en/master/index.html
py3study
2020/01/06
4260
Elasticsearch上手——Pyt
Go Elasticsearch 更新快速入门
本文借助第三方库 olivere/elastic 完成 Go 对 ES 的更新操作。
恋喵大鲤鱼
2021/12/06
3.2K0
Go Elasticsearch 更新快速入门
Go操作Elasticsearch
安装ES 拉取es到本地 docker pull docker.elastic.co/elasticsearch/elasticsearch:7.3.0 创建一个网络 docker network create esnet 启动容器 docker run --name es -p 9200:9200 -p 9300:9300 --network esnet -e "discovery.type=single-node" bdaab402b220 安装ElisticHD docker run -p 980
iginkgo18
2020/09/27
1.5K0
Go操作Elasticsearch
Go每日一库之108:elastic
上一步,我们创建了client,接下来我们就要创建对应的索引以及mapping。根据开始介绍的功能,我们来设计我们的mapping结构:
luckpunk
2023/09/30
5920
ElasticSearch常见用法, 看这一篇就够了
ES中提供了一种强大的检索数据方式,这种检索方式称之为Query DSL,Query DSL是利用Rest API传递JSON格式的请求体(Request Body)数据与ES进行交互,这种方式的丰富查询语法让ES检索变得更强大,更简洁。
架构狂人
2023/09/13
4360
ElasticSearch常见用法, 看这一篇就够了
Python elasticsearch 使用示例
保持热爱奔赴山海
2023/07/31
6490
【ES三周年】ES查询—海量数据搜索深度分页优化
最近在实际项目中查询条件上越来越复杂,mysql的筛选已无法支撑,准备将所有搜索筛选改为es查询。鉴于这种情况,本文调研了from-size,search_after,scroll api, search_after (PIT) 这四种查询优劣。
后面牵个人
2023/04/22
4.4K18
【ES三周年】ES查询—海量数据搜索深度分页优化
03 . Go开发一个日志平台之Elasticsearch使用及kafka消费消息发送到Elasticsearch
https://www.cnblogs.com/you-men/p/13391265.html
iginkgo18
2020/09/27
1.3K0
03 . Go开发一个日志平台之Elasticsearch使用及kafka消费消息发送到Elasticsearch
elasticsearch学习二:导入数据
本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn
仙士可
2022/06/12
8010
ElasticSearch 实用学习笔记 (从入门到精通)
找到 config 下的 kibana.yml 文件,修改最后一行为 i18n.locale: “zh-CN”
Gorit
2021/12/08
2.5K0
Elastic Stack 实战教程 5:Elasticsearch Java API Client 开发
Elastic 在 7.16 版本(2021年12月8日)推出了 Elasticsearch Java API Client。在此之前,我们通常使用 High Level REST Client 进行开发,但是 High Level REST Client 存在几个缺陷:
Se7en258
2023/02/26
2.6K0
Elastic Stack 实战教程 5:Elasticsearch Java API Client 开发
[692]python操作Elasticsearch
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。下面介绍了利用Python API接口进行数据查询,方便其他系统的调用。
周小董
2022/04/13
1.8K0
golang源码分析:go-mysql-elasticsearch(2)
go-mysql-elasticsearch的入口位于:mysql/go-mysql-elasticsearch/cmd/go-mysql-elasticsearch/main.go核心逻辑如下:
golangLeetcode
2023/09/06
3190
golang源码分析:go-mysql-elasticsearch(2)
推荐阅读
相关推荐
Go语言操作Elastic Search v8客户端
更多 >
LV.0
这个人很懒,什么都没有留下~
交个朋友
加入[数据] 腾讯云技术交流站
获取数据实战干货 共享技术经验心得
加入[后端] 腾讯云技术交流站
后端架构设计 高可用系统实现
加入数据技术工作实战群
获取实战干货 交流技术经验
换一批
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档