ElasticSearch - Go语言中文社区

ElasticSearch


ES第三方包

/下面是简单的CURD/

//创建

func create() {

//使用结构体
e1 := Employee{"Jane", "Smith", 32, "I like to collect rock albums", []string{"music"}}
put1, err := client.Index().
    Index("megacorp").
    Type("employee").
    Id("1").
    BodyJson(e1).
    Do(context.Background())
if err != nil {
    panic(err)
}
fmt.Printf("Indexed tweet %s to index s%s, type %sn", put1.Id, put1.Index, put1.Type)

//使用字符串
e2 := `{"first_name":"John","last_name":"Smith","age":25,"about":"I love to go rock climbing","interests":["sports","music"]}`
put2, err := client.Index().
    Index("megacorp").
    Type("employee").
    Id("2").
    BodyJson(e2).
    Do(context.Background())
if err != nil {
    panic(err)
}
fmt.Printf("Indexed tweet %s to index s%s, type %sn", put2.Id, put2.Index, put2.Type)

e3 := `{"first_name":"Douglas","last_name":"Fir","age":35,"about":"I like to build cabinets","interests":["forestry"]}`
put3, err := client.Index().
    Index("megacorp").
    Type("employee").
    Id("3").
    BodyJson(e3).
    Do(context.Background())
if err != nil {
    panic(err)
}
fmt.Printf("Indexed tweet %s to index s%s, type %sn", put3.Id, put3.Index, put3.Type)

}

//删除

func delete() {

res, err := client.Delete().Index("megacorp").
    Type("employee").
    Id("1").
    Do(context.Background())
if err != nil {
    println(err.Error())
    return
}
fmt.Printf("delete result %sn", res.Result)

}

//修改

func update() {
res, err := client.Update().
    Index("megacorp").
    Type("employee").
    Id("2").
    Doc(map[string]interface{}{"age": 88}).
    Do(context.Background())
if err != nil {
    println(err.Error())
}
fmt.Printf("update age %sn", res.Result)}

//查找

func gets() {
//通过id查找
get1, err := client.Get().Index("megacorp").Type("employee").Id("2").Do(context.Background())
if err != nil {
    panic(err)
}
if get1.Found {
    fmt.Printf("Got document %s in version %d from index %s, type %sn", get1.Id, get1.Version, get1.Index, get1.Type)
}}

//搜索

func query() {
var res *elastic.SearchResult
var err error
//取所有
res, err = client.Search("megacorp").Type("employee").Do(context.Background())
printEmployee(res, err)

//字段相等
q := elastic.NewQueryStringQuery("last_name:Smith")
res, err = client.Search("megacorp").Type("employee").Query(q).Do(context.Background())
if err != nil {
    println(err.Error())
}
printEmployee(res, err)

if res.Hits.TotalHits > 0 {
    fmt.Printf("Found a total of %d Employee n", res.Hits.TotalHits)

    for _, hit := range res.Hits.Hits {

        var t Employee
        err := json.Unmarshal(*hit.Source, &t) //另外一种取数据的方法
        if err != nil {
            fmt.Println("Deserialization failed")
        }

        fmt.Printf("Employee name %s : %sn", t.FirstName, t.LastName)
    }
} else {
    fmt.Printf("Found no Employee n")
}

//条件查询
//年龄大于30岁的
boolQ := elastic.NewBoolQuery()
boolQ.Must(elastic.NewMatchQuery("last_name", "smith"))
boolQ.Filter(elastic.NewRangeQuery("age").Gt(30))
res, err = client.Search("megacorp").Type("employee").Query(q).Do(context.Background())
printEmployee(res, err)

//短语搜索 搜索about字段中有 rock climbing
matchPhraseQuery := elastic.NewMatchPhraseQuery("about", "rock climbing")
res, err = client.Search("megacorp").Type("employee").Query(matchPhraseQuery).Do(context.Background())
printEmployee(res, err)

//分析 interests
aggs := elastic.NewTermsAggregation().Field("interests")
res, err = client.Search("megacorp").Type("employee").Aggregation("all_interests", aggs).Do(context.Background())
printEmployee(res, err)

}

//简单分页

func list(size,page int) {
if size < 0 || page < 1 {
    fmt.Printf("param error")
    return
}
res,err := client.Search("megacorp").
    Type("employee").
    Size(size).
    From((page-1)*size).
    Do(context.Background())
    printEmployee(res, err)

}

//打印查询到的Employee

func printEmployee(res *elastic.SearchResult, err error) {
if err != nil {
    print(err.Error())
    return
}
var typ Employee
for _, item := range res.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
    t := item.(Employee)
    fmt.Printf("%#vn", t)
}}

插入

tweet := Tweet{User: "olivere", Message: "Take Five"}
_, err = client.Index().
	Index("tweets").
	Type("doc").
	Id("1").
	BodyJson(tweet).
	Refresh("wait_for").
	Do(context.Background())
if err != nil {
	// Handle error
	panic(err)

按照index查找

temp := client.Get().Index("tweets").Id("1")
get, err := temp.Do(context.Background())
if err != nil {
	logger.L.Debug(err.Error())
}
if get.Found {
	fmt.Printf("Got document %s in version %d from index %s, type %sn", get.Id, get.Version, get.Index, get.Type)
}
source, err := get.Source.MarshalJSON()
if err != nil {
	fmt.Printf("byte convert string failed, err: %v", err)
}
println(source)

教程
es教程
官方API

官方文档
具体操作

在这里插入图片描述
细节

参考链接

  • 每个 Index (即数据库)的名字必须是小写。

  • 查找数据的时候,直接查找该索引。所以,Elastic 数据管理的顶层单位就叫做 Index(索引)。它是单个数据库的同义词。

  • 下面的命令可以查看当前节点的所有 Index。

     	$ curl -X GET 'http://localhost:9200/_cat/indices?v'
    
  • Index 里面单条的记录称为 Document(文档)。许多条 Document 构成了一个 Index。

  • 同一个 Index 里面的 Document,不要求有相同的结构(scheme),但是最好保持相同,这样有利于提高搜索效率。

  • Document 使用 JSON 格式表示

  • Document 可以分组,比如weather这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document。

  • 下面的命令可以列出每个 Index 所包含的 Type。

     		$ curl 'localhost:9200/_mapping?pretty=true'
    
  • Elastic 6.x 版只允许每个 Index 包含一个 Type,7.x 版将会彻底移除 Type。

  • URL 的参数pretty=true表示以易读的格式返回。

  • 上面代码请求查看/accounts/person/1这条记录,URL 的参数pretty=true表示以易读的格式返回。返回的数据中,found字段表示查询成功,_source字段返回原始记录。

  • 在这里插入图片描述在这里插入图片描述

  • 使用 GET 方法,直接请求/Index/Type/_search,就会返回所有记录。

  • 全文搜索

    在这里插入图片描述

  • Elastic 默认一次返回10条结果,可以通过size字段改变这个设置。在这里插入图片描述

  • List item

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42123182/article/details/96861805
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-13 12:15:33
  • 阅读 ( 1764 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢