go使用es:-Go语言中的Elasticsearch操作:olivere实战 - Printf(&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 首码项目 👁️ 218 次阅读

Go语言中的Elasticsearch操作:olivere实战

1. olivere简介

olivere/elastic是Go语言中流行的Elasticsearch客户端库,提供了完整的Elasticsearch API支持。本文将介绍如何使用olivere进行Elasticsearch操作。

2. 安装和连接

go get github.com/olivere/elastic/v7

package main

import (

"context"

"fmt"

"github.com/olivere/elastic/v7"

)

func main() {

client, err := elastic.NewClient(

elastic.SetURL("http://localhost:9200"),

elastic.SetSniff(false),

)

if err != nil {

panic(err)

}

defer client.Stop()

info, code, err := client.Ping("http://localhost:9200").Do(context.Background())

if err != nil {

panic(err)

}

fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

}

3. 索引操作

3.1 创建索引

func createIndex(client *elastic.Client) error {

ctx := context.Background()

mapping := `

{

"settings": {

"number_of_shards": 1,

"number_of_replicas": 0

},

"mappings": {

"properties": {

"title": {

"type": "text"

},

"content": {

"type": "text"

},

"created_at": {

"type": "date"

}

}

}

}`

_, err := client.CreateIndex("articles").BodyString(mapping).Do(ctx)

return err

}

3.2 删除索引

func deleteIndex(client *elastic.Client) error {

ctx := context.Background()

_, err := client.DeleteIndex("articles").Do(ctx)

return err

}

4. 文档操作

4.1 添加文档

type Article struct {

Title string `json:"title"`

Content string `json:"content"`

CreatedAt time.Time `json:"created_at"`

}

func addDocument(client *elastic.Client, article *Article) error {

ctx := context.Background()

_, err := client.Index().

Index("articles").

BodyJson(article).

Do(ctx)

return err

}

4.2 查询文档

func searchDocuments(client *elastic.Client, keyword string) ([]*Article, error) {

ctx := context.Background()

query := elastic.NewMultiMatchQuery(keyword, "title", "content")

result, err := client.Search().

Index("articles").

Query(query).

Sort("created_at", false).

From(0).

Size(10).

Do(ctx)

if err != nil {

return nil, err

}

var articles []*Article

for _, hit := range result.Hits.Hits {

var article Article

err := json.Unmarshal(hit.Source, &article)

if err != nil {

continue

}

articles = append(articles, &article)

}

return articles, nil

}

4.3 更新文档

func updateDocument(client *elastic.Client, id string, article *Article) error {

ctx := context.Background()

_, err := client.Update().

Index("articles").

Id(id).

Doc(article).

Do(ctx)

return err

}

4.4 删除文档

func deleteDocument(client *elastic.Client, id string) error {

ctx := context.Background()

_, err := client.Delete().

Index("articles").

Id(id).

Do(ctx)

return err

}

5. 聚合查询

func aggregateByDate(client *elastic.Client) error {

ctx := context.Background()

agg := elastic.NewDateHistogramAggregation().

Field("created_at").

CalendarInterval("day")

result, err := client.Search().

Index("articles").

Aggregation("by_day", agg).

Do(ctx)

if err != nil {

return err

}

aggResult, found := result.Aggregations.DateHistogram("by_day")

if !found {

return fmt.Errorf("aggregation not found")

}

for _, bucket := range aggResult.Buckets {

fmt.Printf("Date: %s, Count: %d\n", *bucket.KeyAsString, bucket.DocCount)

} 拼多多帮助力入口

return nil

}

6. 总结

使用olivere/elastic时应注意:

合理设置索引的mapping和settings使用批量操作提高效率配置合适的查询超时使用聚合进行数据分析监控集群健康状态

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧