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