golang Elasticsearch客户端库插件elastigo的使用
Golang Elasticsearch客户端库插件elastigo的使用
elastigo v2.0
elastigo是一个基于Go语言的Elasticsearch客户端库,实现了索引和搜索的核心API功能。
快速开始
使用Docker运行Elasticsearch
docker run -d -p 9200:9200 -p 9300:9300 dockerfile/elasticsearch
安装elastigo
git clone git@github.com:mattbaird/elastigo.git
cd elastigo
go get -u ./...
使用示例
添加内容到Elasticsearch
import "github.com/mattbaird/elastigo/api"
import "github.com/mattbaird/elastigo/core"
type Tweet struct {
User string `json:"user"`
Message string `json:"message"`
}
// 设置Elasticsearch连接主机
api.Domain = "localhost"
// 添加单个Go结构体实体
response, _ := core.Index("twitter", "tweet", "1", nil, Tweet{"kimchy", "Search is cool"})
// 使用字节数据
tw := Tweet{"kimchy", "Search is cool part 2"}
bytesLine, err := json.Marshal(tw)
response, _ := core.Index("twitter", "tweet", "2", nil, bytesLine)
// 批量索引
t := time.Now()
core.IndexBulk("twitter", "tweet", "3", &t, Tweet{"kimchy", "Search is now cooler"})
// 使用原始JSON字符串搜索
searchJson := `{
"query" : {
"term" : { "user" : "kimchy" }
}
}`
out, err := core.SearchRequest(true, "twitter", "tweet", searchJson, "")
if len(out.Hits.Hits) == 1 {
fmt.Println(string(out.Hits.Hits[0].Source))
}
使用Search DSL进行分面、范围搜索
import "github.com/mattbaird/elastigo/api"
import "github.com/mattbaird/elastigo/core"
// 设置Elasticsearch连接主机
api.Domain = "localhost"
out, err := Search("github").Size("1").Facet(
Facet().Fields("actor").Size("500"),
).Query(
Query().Range(
Range().Field("created_at").From("2012-12-10T15:00:00-08:00").To("2012-12-10T15:10:00-08:00"),
).Search("add"),
).Result()
使用Search DSL进行范围搜索
out, err := Search("github").Type("Issues").Pretty().Query(
Query().Range(
Range().Field("created_at").From("2012-12-10T15:00:00-08:00").To("2012-12-10T15:10:00-08:00"),
).Search("add"),
).Result()
使用Search DSL进行简单搜索
out, err := Search("github").Type("Issues").Size("100").Search("add").Result()
直接使用API搜索
qry := map[string]interface{}{
"query":map[string]interface{}{
"term":map[string]string{"user": "kimchy"},
},
}
core.SearchRequest(true, "github", "Issues", qry, "", 0)
使用查询字符串API直接搜索
core.SearchUri("github", "Issues", "user:kimchy", "", 0)
使用Search DSL进行过滤搜索
out, err := Search("github").Filter(
Filter().Exists("repository.name"),
).Result()
批量添加内容到Elasticsearch
import "github.com/mattbaird/elastigo/api"
import "github.com/mattbaird/elastigo/core"
// 设置Elasticsearch连接主机
api.Domain = "localhost"
indexer := core.NewBulkIndexerErrors(10, 60)
done := make(chan bool)
indexer.Run(done)
go func() {
for errBuf := range indexer.ErrorChannel {
// 持续打印错误
fmt.Println(errBuf.Err)
}
}()
for i := 0; i < 20; i++ {
indexer.Index("twitter", "user", strconv.Itoa(i), "", nil, `{"name":"bob"}`, false)
}
done <- true
// 索引可能需要一些时间,因此在main函数中确保程序运行足够长时间
许可证
Copyright 2012 Matthew Baird, Aaron Raddon, Jeremy Shute and more!
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
更多关于golang Elasticsearch客户端库插件elastigo的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang Elasticsearch客户端库插件elastigo的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Elastigo - Elasticsearch Go 客户端库使用指南
elastigo 是一个 Go 语言的 Elasticsearch 客户端库,提供了与 Elasticsearch 交互的简单接口。虽然官方现在推荐使用 olivere/elastic,但 elastigo 仍然是一个轻量级的选择。
安装
go get github.com/mattbaird/elastigo/lib
基本使用
1. 初始化连接
package main
import (
"fmt"
"github.com/mattbaird/elastigo/lib"
)
func main() {
// 创建连接器
conn := lib.NewConn()
// 设置Elasticsearch服务器地址
conn.Domain = "localhost"
conn.Port = "9200"
// 测试连接
_, err := conn.Health()
if err != nil {
panic(err)
}
fmt.Println("Connected to Elasticsearch")
}
2. 创建索引
func createIndex(conn *lib.Conn) {
// 创建索引
_, err := conn.CreateIndex("myindex")
if err != nil {
fmt.Printf("Error creating index: %v\n", err)
} else {
fmt.Println("Index created successfully")
}
// 可选:设置映射
mapping := `{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
},
"mappings": {
"properties": {
"title": {"type": "text"},
"content": {"type": "text"},
"timestamp": {"type": "date"}
}
}
}`
_, err = conn.DoCommand("PUT", "/myindex", nil, mapping)
if err != nil {
fmt.Printf("Error setting mapping: %v\n", err)
}
}
3. 索引文档
func indexDocument(conn *lib.Conn) {
doc := map[string]interface{}{
"title": "Elastigo Example",
"content": "This is an example document for elastigo",
"timestamp": "2023-01-01T00:00:00Z",
}
_, err := conn.Index("myindex", "mytype", "1", nil, doc)
if err != nil {
fmt.Printf("Error indexing document: %v\n", err)
} else {
fmt.Println("Document indexed successfully")
}
}
4. 搜索文档
func searchDocuments(conn *lib.Conn) {
query := `{
"query": {
"match": {
"content": "example"
}
}
}`
out, err := conn.Search("myindex", "mytype", nil, query)
if err != nil {
fmt.Printf("Error searching: %v\n", err)
return
}
fmt.Printf("Found %d hits\n", out.Hits.Total)
for _, hit := range out.Hits.Hits {
fmt.Printf("ID: %s, Source: %v\n", hit.Id, hit.Source)
}
}
5. 更新文档
func updateDocument(conn *lib.Conn) {
update := map[string]interface{}{
"doc": map[string]interface{}{
"content": "Updated content for elastigo example",
},
}
_, err := conn.Update("myindex", "mytype", "1", nil, update)
if err != nil {
fmt.Printf("Error updating document: %v\n", err)
} else {
fmt.Println("Document updated successfully")
}
}
6. 删除文档和索引
func deleteOperations(conn *lib.Conn) {
// 删除文档
_, err := conn.Delete("myindex", "mytype", "1", nil)
if err != nil {
fmt.Printf("Error deleting document: %v\n", err)
} else {
fmt.Println("Document deleted successfully")
}
// 删除索引
_, err = conn.DeleteIndex("myindex")
if err != nil {
fmt.Printf("Error deleting index: %v\n", err)
} else {
fmt.Println("Index deleted successfully")
}
}
高级功能
批量操作
func bulkOperations(conn *lib.Conn) {
bulk := conn.NewBulkIndexRequest()
// 添加多个索引操作
doc1 := map[string]interface{}{"title": "Bulk Doc 1", "content": "Content 1"}
doc2 := map[string]interface{}{"title": "Bulk Doc 2", "content": "Content 2"}
bulk.Add("myindex", "mytype", "2", nil, doc1)
bulk.Add("myindex", "mytype", "3", nil, doc2)
// 执行批量操作
_, err := bulk.Do()
if err != nil {
fmt.Printf("Error in bulk operation: %v\n", err)
} else {
fmt.Println("Bulk operations completed successfully")
}
}
使用过滤器
func filteredSearch(conn *lib.Conn) {
query := `{
"query": {
"bool": {
"must": {
"match": {"content": "example"}
},
"filter": {
"range": {
"timestamp": {
"gte": "2022-01-01",
"lte": "2023-12-31"
}
}
}
}
}
}`
out, err := conn.Search("myindex", "mytype", nil, query)
if err != nil {
fmt.Printf("Error in filtered search: %v\n", err)
return
}
fmt.Printf("Filtered search found %d hits\n", out.Hits.Total)
}
注意事项
- elastigo 已经不再积极维护,对于新项目建议考虑官方推荐的客户端
- 生产环境中应该处理连接池和错误重试
- 对于复杂查询,建议使用结构体而不是原始JSON字符串
- 记得在完成操作后关闭连接
elastigo 提供了基本的 Elasticsearch 操作接口,适合简单的用例。对于更复杂的场景,可能需要考虑功能更全面的客户端库。