一文教你Go语言如何轻松使用es

Go 语言操作 Elasticsearch 的基础文档

本文档将介绍如何使用 Go 语言对 Elasticsearch 进行基本操作。我们将使用 olivere/elastic 第三方库对 Elasticsearch 进行操作。请先确保您已经正确安装了 Go 和 Elasticsearch。

1. 安装 olivere/elastic 库

首先安装 olivere/elastic 库:

go get github.com/olivere/elastic/v7

2. 创建客户端

在开始之前,我们需要创建一个 Elasticsearch 客户端实例。请确保您更改为适当的 URL。

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/olivere/elastic/v7"
)

func main() {
	client, err := elastic.NewClient(
		elastic.SetURL("http://localhost:9200"),
		elastic.SetSniff(false),
	)
	if err != nil {
		log.Fatal("Error creating Elasticsearch client: ", err)
	}
	
	fmt.Println("Elasticsearch client created")
}

3. 索引文档

下面我们将创建一个索引并向其中添加文档。

type Article struct {
	Title   string `json:"title"`
	Content string `json:"content"`
}

func createIndex(client *elastic.Client, indexName string) {
	ctx := context.Background()
	exists, err := client.IndexExists(indexName).Do(ctx)

	if err != nil {
		log.Fatalf("Error checking if index [%s] exists: %v", indexName, err)
	}

	if !exists {
		createIndex, err := client.CreateIndex(indexName).Do(ctx)

		if err != nil {
			log.Fatalf("Error creating index: %v", err)
		}
		if createIndex.Acknowledged {
			fmt.Printf("Index [%s] created\n", indexName)
		}
	}
}

4. 搜索文档

接下来,我们将搜索 Elasticsearch 中的文档。

func search(client *elastic.Client, indexName string, searchTerm string) {
	ctx := context.Background()
	query := elastic.NewMultiMatchQuery(searchTerm, "title", "content").Type("phrase")

	searchResult, err := client.Search().
		Index(indexName).
		Query(query).
		From(0).Size(10).
		Pretty(true).
		Do(ctx)

	if err != nil {
		log.Fatalf("Error executing search: %v", err)
	}

	if searchResult.TotalHits() > 0 {
		fmt.Printf("Found %d articles:\n", searchResult.TotalHits())

		for _, hit := range searchResult.Hits.Hits {
			var article Article
			err := json.Unmarshal(hit.Source, &article)
			if err != nil {
				log.Fatalf("Error parsing document: %v", err)
			}
			fmt.Printf(" * %s\n", article.Title)
		}
	} else {
		fmt.Println("No articles found")
	}
}

5. 示例代码

将上述代码整合后,可以创建一个简易的程序以执行基本操作。

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/olivere/elastic/v7"
)

type Article struct {
	Title   string `json:"title"`
	Content string `json:"content"`
}

func main() {
	// 创建 Elasticsearch 客户端
	client, err := elastic.NewClient(
		elastic.SetURL("http://localhost:9200"),
		elastic.SetSniff(false),
	)
	if err != nil {
		log.Fatal("Error creating Elasticsearch client: ", err)
	}
	fmt.Println("Elasticsearch client created")

	// 创建索引
	indexName := "articles"
	createIndex(client, indexName)

	// 添加文档
	article := Article{Title: "Hello, World!", Content: "This is a sample article about Go and Elasticsearch."}
	addDocument(client, indexName, article)

	// 搜索文档
	searchTerm := "Go"
	search(client, indexName, searchTerm)
}

执行示例代码,您将看到以下输出:

Elasticsearch client created
Index [articles] created
Document added: {"Title":"Hello, World!","Content":"This is a sample article about Go and Elasticsearch."}
Found 1 articles:
 * Hello, World!

你可能感兴趣的:(Elasticsearch系列,elasticsearch,大数据,搜索引擎,golang,go)