Golang操作ES

这篇博客详细介绍了如何使用Golang与Elasticsearch进行交互,包括创建项目、安装包、连接ES、操作索引(创建、查询、删除)、插入、查询和删除文档。还演示了如何在Gin框架中集成Elasticsearch,实现查询和显示结果的功能。
摘要由CSDN通过智能技术生成


Golang操作ES快速入门

创建项目

创建一个项目demo,初始化项目go mod init demo

安装包

go get github.com/elastic/go-elasticsearch/v7

连接到ES

package main

import (
	"log"

	"github.com/elastic/go-elasticsearch/v7"
)

func main() {
   
	es, err := elasticsearch.NewDefaultClient()// 连接到es服务器
	if err != nil {
   
		panic(err)
	}
	log.Println(elasticsearch.Version)
	log.Println(es.Info())
}

运行结果

[Running] go run "e:\golang开发学习\es\main.go"
2022/09/24 13:16:22 7.17.1
2022/09/24 13:16:22 [200 OK] {
   
  "name" : "MORAX",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "HoU0Tw3WTiSMD2GRzezqnw",
  "version" : {
   
    "number" : "7.8.1",
    "build_flavor" : "default",
    "build_type" : "zip",
    "build_hash" : "b5ca9c58fb664ca8bf9e4057fc229b3396bf3a89",
    "build_date" : "2020-07-21T16:40:44.668009Z",
    "build_snapshot" : false,
    "lucene_version" : "8.5.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
 <nil>

[Done] exited with code=0 in 2.516 seconds

Golang操作ES索引

es API

我们获得es客户端实例后,通过客户端实例可以获得es api,内容如下:

package esapi

// API contains the Elasticsearch APIs
//
type API struct {
   
	Cat         *Cat
	Cluster     *Cluster
	Indices     *Indices
	Ingest      *Ingest
	Nodes       *Nodes
	Remote      *Remote
	Snapshot    *Snapshot
	Tasks       *Tasks
	AsyncSearch *AsyncSearch
	CCR         *CCR
	ILM         *ILM
	License     *License
	Migration   *Migration
	ML          *ML
	Monitoring  *Monitoring
	Rollup      *Rollup
	Security    *Security
	SQL         *SQL
	SSL         *SSL
	Watcher     *Watcher
	XPack       *XPack

	AutoscalingDeleteAutoscalingPolicy            AutoscalingDeleteAutoscalingPolicy
	AutoscalingGetAutoscalingCapacity             AutoscalingGetAutoscalingCapacity
	AutoscalingGetAutoscalingDecision             AutoscalingGetAutoscalingDecision
	AutoscalingGetAutoscalingPolicy               AutoscalingGetAutoscalingPolicy
	AutoscalingPutAutoscalingPolicy               AutoscalingPutAutoscalingPolicy
	Bulk                                          Bulk
	ClearScroll                                   ClearScroll
	ClosePointInTime                              ClosePointInTime
	Count                                         Count
	Create                                        Create
	DanglingIndicesDeleteDanglingIndex            DanglingIndicesDeleteDanglingIndex
	DanglingIndicesImportDanglingIndex            DanglingIndicesImportDanglingIndex
	DanglingIndicesListDanglingIndices            DanglingIndicesListDanglingIndices
	DataFrameTransformDeprecatedDeleteTransform   DataFrameTransformDeprecatedDeleteTransform
	DataFrameTransformDeprecatedGetTransform      DataFrameTransformDeprecatedGetTransform
	DataFrameTransformDeprecatedGetTransformStats DataFrameTransformDeprecatedGetTransformStats
	DataFrameTransformDeprecatedPreviewTransform  DataFrameTransformDeprecatedPreviewTransform
	DataFrameTransformDeprecatedPutTransform      DataFrameTransformDeprecatedPutTransform
	DataFrameTransformDeprecatedStartTransform    DataFrameTransformDeprecatedStartTransform
	DataFrameTransformDeprecatedStopTransform     DataFrameTransformDeprecatedStopTransform
	DataFrameTransformDeprecatedUpdateTransform   DataFrameTransformDeprecatedUpdateTransform
	DeleteByQuery                                 DeleteByQuery
	DeleteByQueryRethrottle                       DeleteByQueryRethrottle
	Delete                                        Delete
	DeleteScript                                  DeleteScript
	EnrichDeletePolicy                            EnrichDeletePolicy
	EnrichExecutePolicy                           EnrichExecutePolicy
	EnrichGetPolicy                               EnrichGetPolicy
	EnrichPutPolicy                               EnrichPutPolicy
	EnrichStats                                   EnrichStats
	EqlDelete                                     EqlDelete
	EqlGet                                        EqlGet
	EqlGetStatus                                  EqlGetStatus
	EqlSearch                                     EqlSearch
	Exists                                        Exists
	ExistsSource                                  ExistsSource
	Explain                                       Explain
	FeaturesGetFeatures                           FeaturesGetFeatures
	FeaturesResetFeatures                         FeaturesResetFeatures
	FieldCaps                                     FieldCaps
	FleetGlobalCheckpoints                        FleetGlobalCheckpoints
	FleetMsearch                                  FleetMsearch
	FleetSearch                                   FleetSearch
	Get                                           Get
	GetScriptContext                              GetScriptContext
	GetScriptLanguages                            GetScriptLanguages
	GetScript                                     GetScript
	GetSource                                     GetSource
	GraphExplore                                  GraphExplore
	Index                                         Index
	Info                                          Info
	LogstashDeletePipeline                        LogstashDeletePipeline
	LogstashGetPipeline                           LogstashGetPipeline
	LogstashPutPipeline                           LogstashPutPipeline
	Mget                                          Mget
	Msearch                                       Msearch
	MsearchTemplate                               MsearchTemplate
	Mtermvectors                                  Mtermvectors
	OpenPointInTime                               OpenPointInTime
	Ping                                          Ping
	PutScript                                     PutScript
	RankEval                                      RankEval
	Reindex                                       Reindex
	ReindexRethrottle                             ReindexRethrottle
	RenderSearchTemplate                          RenderSearchTemplate
	ScriptsPainlessExecute                        ScriptsPainlessExecute
	Scroll                                        Scroll
	SearchMvt                                     SearchMvt
	Search                                        Search
	SearchShards                                  SearchShards
	SearchTemplate                                SearchTemplate
	SearchableSnapshotsCacheStats                 SearchableSnapshotsCacheStats
	SearchableSnapshotsClearCache                 SearchableSnapshotsClearCache
	SearchableSnapshotsMount                      SearchableSnapshotsMount
	SearchableSnapshotsRepositoryStats            SearchableSnapshotsRepositoryStats
	SearchableSnapshotsStats                      SearchableSnapshotsStats
	ShutdownDeleteNode                            ShutdownDeleteNode
	ShutdownGetNode                               ShutdownGetNode
	ShutdownPutNode                               ShutdownPutNode
	SlmDeleteLifecycle                            SlmDeleteLifecycle
	SlmExecuteLifecycle                           SlmExecuteLifecycle
	SlmExecuteRetention                           SlmExecuteRetention
	SlmGetLifecycle                               SlmGetLifecycle
	SlmGetStats                                   SlmGetStats
	SlmGetStatus                                  SlmGetStatus
	SlmPutLifecycle                               SlmPutLifecycle
	SlmStart                                      SlmStart
	SlmStop                                       SlmStop
	TermsEnum                                     TermsEnum
	Termvectors                                   Termvectors
	TextStructureFindStructure                    TextStructureFindStructure
	TransformDeleteTransform                      TransformDeleteTransform
	TransformGetTransform                         TransformGetTransform
	TransformGetTransformStats                    TransformGetTransformStats
	TransformPreviewTransform                     TransformPreviewTransform
	TransformPutTransform                         TransformPutTransform
	TransformStartTransform                       TransformStartTransform
	TransformStopTransform                        TransformStopTransform
	TransformUpdateTransform                      TransformUpdateTransform
	TransformUpgradeTransforms                    TransformUpgradeTransforms
	UpdateByQuery                                 UpdateByQuery
	UpdateByQueryRethrottle                       UpdateByQueryRethrottle
	Update                                        Update
}

API结构体里面包含了Indices,内容如下:

// Indices contains the Indices APIs
type Indices struct {
   
	AddBlock              IndicesAddBlock
	Analyze               IndicesAnalyze
	ClearCache            IndicesClearCache
	Clone                 IndicesClone
	Close                 IndicesClose
	CreateDataStream      IndicesCreateDataStream
	Create                IndicesCreate
	DataStreamsStats      IndicesDataStreamsStats
	DeleteAlias           IndicesDeleteAlias
	DeleteDataStream      IndicesDeleteDataStream
	DeleteIndexTemplate   IndicesDeleteIndexTemplate
	Delete                IndicesDelete
	DeleteTemplate        IndicesDeleteTemplate
	DiskUsage             IndicesDiskUsage
	ExistsAlias           IndicesExistsAlias
	ExistsDocumentType    IndicesExistsDocumentType
	ExistsIndexTemplate   IndicesExistsIndexTemplate
	Exists                IndicesExists
	ExistsTemplate        IndicesExistsTemplate
	FieldUsageStats       IndicesFieldUsageStats
	Flush                 IndicesFlush
	FlushSynced           IndicesFlushSynced
	Forcemerge            IndicesForcemerge
	Freeze                IndicesFreeze
	GetAlias              IndicesGetAlias
	GetDataStream         IndicesGetDataStream
	GetFieldMapping       IndicesGetFieldMapping
	GetIndexTemplate      IndicesGetIndexTemplate
	GetMapping            IndicesGetMapping
	Get                   IndicesGet
	GetSettings           IndicesGetSettings
	GetTemplate           IndicesGetTemplate
	GetUpgrade            IndicesGetUpgrade
	MigrateToDataStream   IndicesMigrateToDataStream
	ModifyDataStream      IndicesModifyDataStream
	Open                  IndicesOpen
	PromoteDataStream     IndicesPromoteDataStream
	PutAlias              IndicesPutAlias
	PutIndexTemplate      IndicesPutIndexTemplate
	PutMapping            IndicesPutMapping
	PutSettings           IndicesPutSettings
	PutTemplate           IndicesPutTemplate
	Recovery              IndicesRecovery
	Refresh               IndicesRefresh
	ReloadSearchAnalyzers IndicesReloadSearchAnalyzers
	ResolveIndex          IndicesResolveIndex
	Rollover              IndicesRollover
	Segments              IndicesSegments
	ShardStores           IndicesShardStores
	Shrink                IndicesShrink
	SimulateIndexTemplate IndicesSimulateIndexTemplate
	SimulateTemplate      IndicesSimulateTemplate
	Split                 IndicesSplit
	Stats                 IndicesStats
	Unfreeze              IndicesUnfreeze
	UpdateAliases         IndicesUpdateAliases
	Upgrade               IndicesUpgrade
	ValidateQuery         IndicesValidateQuery
}

该结构体包含了操作索引的一些方法,例如:创建索引Create、查询索引Get、删除索引Delete

创建索引

创建索引函数如下:

type IndicesCreate func(index string, o ...func(*IndicesCreateRequest)) (*Response, error)

只要传入一个创建索引的名称即可,也可以通过IndicesCreateRequest传递一些创建索引的额外信息

实例演示:

package main

import (
	"fmt"
	"log"

	"github.com/elastic/go-elasticsearch/v7"
)

// 创建索引
func CreatIndex(client *elasticsearch.Client, name string) {
   
	r, _ := client.API.Indices.Create(name)
	fmt.Printf("r: %v\n", r)
}

func main() {
   
	es, err := elasticsearch.NewDefaultClient()
	if err != nil {
   
		log.Fatalf("获取es客户端错误: %s", err)
	}
	CreatIndex(es, "es_test")
}

运行结果:

[Running] go run "e:\golang开发学习\es\main.go"
r: [200 OK] {
   "acknowledged":true,"shards_acknowledged":true,"index":"es_test"}

[Done] exited with code=0 in 3.902 seconds

查询索引

查询索引函数如下:

type IndicesGet func(index []string, o ...func(*IndicesGetRequest)) (*Response, error)

传入需要查询的字符串切片即可

实例演示:

package main

import (
	"fmt"
	"log"

	"github.com/elastic/go-elasticsearch/v7"
)

// 查询索引
func GetIndex(client *elasticsearch.Client, name string) {
   
	r, _ := client.API.Indices.Get([]string{
   name})
	fmt.Printf("r: %v\n", r)
}

func main() {
   
	es, err := elasticsearch.NewDefaultClient()
	if err != nil {
   
		log.Fatalf("获取es客户端错误: %s", err)
	}
	GetIndex
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Elasticsearch是一个开源的分布式搜索和分析引擎,它提供了强大的全文搜索、结构化查询、分析能力和实时数据分析等功能。而Golang是一种编程语言,也被称为Go语言,它具有高效、简洁、并发安全等特点。 在Golang中使用Elasticsearch可以通过第三方库进行操作,最常用的是官方提供的Elasticsearch客户端库——"github.com/elastic/go-elasticsearch"。这个库提供了与Elasticsearch进行交互的API,可以进行索引、搜索、聚合等操作。 使用go-elasticsearch库,你可以通过以下步骤来使用Elasticsearch: 1. 安装go-elasticsearch库:在终端中执行命令`go get github.com/elastic/go-elasticsearch/v8`来安装该库。 2. 导入库:在你的Go代码中导入"go.elastic.co/elasticsearch/v8"。 3. 创建Elasticsearch客户端:使用库提供的`elasticsearch.NewClient()`函数创建一个Elasticsearch客户端实例。 4. 执行操作:通过客户端实例调用相应的API方法来执行索引、搜索、聚合等操作。 以下是一个简单的示例代码,展示了如何使用go-elasticsearch库进行基本的索引和搜索操作: ```go package main import ( "context" "fmt" "log" "github.com/elastic/go-elasticsearch/v8" ) func main() { // 创建Elasticsearch客户端 cfg := elasticsearch.Config{ Addresses: []string{"http://localhost:9200"}, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } // 索引文档 doc := `{"title" : "Elasticsearch Golang Example"}` res, err := es.Index("my-index", strings.NewReader(doc)) if err != nil { log.Fatalf("Error indexing document: %s", err) } defer res.Body.Close() // 搜索文档 var buf bytes.Buffer query := map[string]interface{}{ "query": map[string]interface{}{ "match": map[string]interface{}{ "title": "example", }, }, } if err := json.NewEncoder(&buf).Encode(query); err != nil { log.Fatalf("Error encoding query: %s", err) } res, err = es.Search( es.Search.WithContext(context.Background()), es.Search.WithIndex("my-index"), es.Search.WithBody(&buf), es.Search.WithTrackTotalHits(true), es.Search.WithPretty(), ) if err != nil { log.Fatalf("Error searching for documents: %s", err) } defer res.Body.Close() // 处理搜索结果 var r map[string]interface{} if err := json.NewDecoder(res.Body).Decode(&r); err != nil { log.Fatalf("Error parsing the response body: %s", err) } fmt.Println(r) } ``` 这只是一个简单的示例,你可以根据自己的需求进行更复杂的操作。你可以参考go-elasticsearch库的文档(https://pkg.go.dev/github.com/elastic/go-elasticsearch/v8)来了解更多关于使用ElasticsearchGolang的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值