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

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

1. olivere简介

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

2. 安装和连接

bash 复制代码
go get github.com/olivere/elastic/v7
go 复制代码
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 创建索引

go 复制代码
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 删除索引

go 复制代码
func deleteIndex(client *elastic.Client) error {
	ctx := context.Background()
	_, err := client.DeleteIndex("articles").Do(ctx)
	return err
}

4. 文档操作

4.1 添加文档

go 复制代码
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 查询文档

go 复制代码
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 更新文档

go 复制代码
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 删除文档

go 复制代码
func deleteDocument(client *elastic.Client, id string) error {
	ctx := context.Background()
	_, err := client.Delete().
		Index("articles").
		Id(id).
		Do(ctx)
	return err
}

5. 聚合查询

go 复制代码
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时应注意:

  1. 合理设置索引的mapping和settings
  2. 使用批量操作提高效率
  3. 配置合适的查询超时
  4. 使用聚合进行数据分析
  5. 监控集群健康状态
相关推荐
GetcharZp14 分钟前
5 分钟拥有自己的 S3:RustFS 上手(MinIO 的 Rust 替代,Apache 2.0 可商用)
后端
行百里er1 小时前
Redis 版本演进、新特性与协议那些事儿
redis·后端
Joy T1 小时前
Spring AI 2.0 Agent 进阶:Memory、State 与 Context Engineering 常见技术全景
java·人工智能·后端·spring·agent入门·agent state
打工仔折腾 AI2 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
IT_陈寒2 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端
moMo3 小时前
LangChain 到 LangGraph: RAG 知识库改造
后端
用户574385305113 小时前
元数据驱动的通用 CRUD 后端框架 (3- createBusiness 工厂:三层装配 + 一行出 REST)
后端
高级程序源3 小时前
django大学生创新创业项目管理系统94923-计算机课程设计、毕业设计
javascript·vue.js·spring boot·后端·python·django·课程设计
Sam_Deep_Thinking3 小时前
new Thread()之后发生了什么?
java·后端·面试·程序员