赞
踩
本文档将介绍如何使用 Go 语言对 Elasticsearch 进行基本操作。我们将使用 olivere/elastic 第三方库对 Elasticsearch 进行操作。请先确保您已经正确安装了 Go 和 Elasticsearch。
首先安装 olivere/elastic
库:
go get github.com/olivere/elastic/v7
在开始之前,我们需要创建一个 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") }
下面我们将创建一个索引并向其中添加文档。
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) } } }
接下来,我们将搜索 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") } }
将上述代码整合后,可以创建一个简易的程序以执行基本操作。
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!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。