package main
import (
"context"
"fmt"
"time"
"gopkg.in/olivere/elastic.v6"
)
var host = "http://127.0.0.1:9200"
func main() {
ctx := context.Background()
client, err := ElasticInit(host)
if err != nil {
fmt.Println(err)
}
Exist(client, ctx) // 创建index
AddData(client, ctx) // 增加数据
// 插入完成之后可以用这条命令去查看数据是否插入成功
// curl -H "Content-Type: application/json" http://localhost:9200/twitter/_search\?pretty -d ' {"query": {"match_all": {}}}'
time.Sleep(10 * time.Second)
DelMember(client, ctx) // 删除数据
}
type Tweet struct {
User string `json:"user"`
Message string `json:"message"`
Retweets int `json:"retweets"`
Image string `json:"image,omitempty"`
Created time.Time `json:"created,omitempty"`
Tags []string `json:"tags,omitempty"`
Location string `json:"location,omitempty"`
Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
}
const mapping = `
{
"settings":{
"number_of_shards": 1,
"number_of_replicas": 0
},
"mappings":{
"tweet":{
"properties":{
"user":{
"type":"keyword"
},
"message":{
"type":"text",
"store": true,
"fielddata": true
},
"image":{
"type":"keyword"
},
"created":{
"type":"date"
},
"tags":{
"type":"keyword"
},
"location":{
"type":"geo_point"
},
"suggest_field":{
"type":"completion"
}
}
}
}
}`
// 创建index
func Exist(client *elastic.Client, ctx context.Context) {
exists, err := client.IndexExists("twitter").Do(ctx)
if err != nil {
panic(err)
}
if !exists {
createIndex, err := client.CreateIndex("twitter").BodyString(mapping).Do(ctx)
if err != nil {
panic(err)
}
if !createIndex.Acknowledged { // 没有确认
}
}
}
// 增加数据
func AddData(client *elastic.Client, ctx context.Context) {
tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
put1, err := client.Index().
Index("twitter").
Type("tweet").
Id("1").
BodyJson(tweet1).
Do(ctx)
if err != nil {
panic(err)
}
fmt.Println(put1.Id, put1.Index, put1.Status, put1.Type, put1.Version)
}
// 删除数据
func DelMember(client *elastic.Client, ctx context.Context) error {
// 先搜索判断要删除的数据时候存在,是否只有一条,满足这两个条件就直接删除
// 这个是查询是否存在也可以不要活着自己优化一下
boolQ := elastic.NewBoolQuery()
boolQ.Filter(elastic.NewTermQuery("user", "olivere"))
searchQuery := client.Search().Query(boolQ).Index("twitter").Type("tweet")
result, err := searchQuery.Do(ctx)
if err != nil {
return err
}
fmt.Println(result.Hits, "++++++++++++++=") //
// 删除
result2, err := elastic.NewDeleteByQueryService(client).Index("twitter").Type("tweet").Query(boolQ).Do(ctx)
fmt.Println(err, result2, "+============") //这里需要判断一下是否成功,或者是否出错
return nil
}
//初始化
func ElasticInit(host string) (*elastic.Client, error) {
client, err := elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false))
if err != nil {
panic(err)
}
_, _, err = client.Ping(host).Do(context.Background())
if err != nil {
panic(err)
}
_, err = client.ElasticsearchVersion(host)
if err != nil {
panic(err)
}
return client, err
}
网友评论