在 Go 中,可以使用官方 Elasticsearch 客户端库来进行索引和文档操作。以下是一些示例:
创建索引
import (
"context"
"github.com/elastic/go-elasticsearch/v7"
)
func main() {
es, _ := elasticsearch.NewDefaultClient()
var mapping = `
{
"mappings": {
"properties": {
"name": { "type": "text" },
"age": { "type": "integer" }
}
}
}`
res, err := es.Indices.Create(
[]string{"my-index"},
es.Indices.Create.WithBody(strings.NewReader(mapping)),
es.Indices.Create.WithPretty(),
)
if err != nil {
log.Fatalf("Error creating index: %s", err)
}
}
删除索引
res, err := es.Indices.Delete([]string{"my-index"}, es.Indices.Delete.WithPretty())
if err != nil {
log.Fatalf("Error deleting index: %s", err)
}
defer res.Body.Close()
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
fmt.Println(r["acknowledged"])
}
插入文档
doc := map[string]interface{}{
"name": "John Doe",
"age": 30,
}
// 使用自动生成的 ID 插入文档
res, err := es.Index("my-index", doc)
if err != nil {
log.Fatalf("Error indexing document: %s", err)
}
defer res.Body.Close()
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
fmt.Println(r["_id"])
}
// 使用指定的 ID 插入文档
res, err = es.Index("my-index", strings.NewReader(`{"name": "Jane Doe", "age": 25}`),
es.Index.WithDocumentID("2"))
if err != nil {
log.Fatalf("Error indexing document: %s", err)
}
defer res.Body.Close()
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
fmt.Println(r["_id"])
}
获取文档
res, err := es.Get("my-index", "1")
if err != nil {
log.Fatalf("Error getting document: %s", err)
}
defer res.Body.Close()
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
source := r["_source"].(map[string]interface{})
fmt.Println(source["name"], source["age"])
}
更新文档
doc := map[string]interface{}{
"name": "John Smith",
"age": 35,
}
res, err := es.Update(
"my-index",
"1",
es.Update.WithDoc(doc),
es.Update.WithRetryOnConflict(3),
es.Update.WithPretty(),
)
if err != nil {
log.Fatalf("Error updating document: %s", err)
}
defer res.Body.Close()
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
fmt.Println(r["_id"])
}
删除文档
res, err := es.Delete("my-index", "1")
if err != nil {
log.Fatalf("Error deleting document: %s", err)
}
defer res.Body.Close()
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
fmt.Println(r["_id"])
}
以上是在 Go 中使用官方 Elasticsearch 客户端库进行索引和文档操作的一些示例。可以根据具体需求来选择合适的选项和参数。