当前位置:   article > 正文

go操作es7的常用增删改查操作_go es修改

go es修改

go操作es7的常用增删改查操作

说明: 为了更好的操作,该文件放置一个文件. 有需要的伙伴可以进行提取封装
文件下载地址: https://github.com/yunziyuan/cntech-go

1.初始化连接es

使用时,修改es的地址

  var ctx = context.Background()
  var esUrl = "http://127.0.0.1:7010"
  var EsClient *elastic.Client
  
  // 初始化es连接
  func InitEs() {
      // 连接es客户端
      client, err := elastic.NewClient(
          elastic.SetURL(esUrl),
      )
      if err != nil {
          log.Fatal("es 连接失败:", err)
      }
      // ping通服务端,并获得服务端的es版本,本实例的es版本为version 7.6.1
      info, code, err := client.Ping(esUrl).Do(ctx)
      if err != nil {
          // Handle error
          panic(err)
      }
      fmt.Println("Elasticsearch returned with code>: %d and version %s\n", code, info.Version.Number)
  
      EsClient = client
      fmt.Println("es连接成功")
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
2.新增索引及数据结构

数据索引是为了为es指定字段类型

  // 定义数据结构体
  type data struct {
  	Id   string `json:"id"`
  	Icon string `json:"icon"`
  	Name string `json:"name"`
  	Age  int    `json:"age"`
  }
  
  // 定义一些变量,mapping为定制的index字段类型
  const mapping = `
  {
  	"settings":{
  		"number_of_shards": 1,
  		"number_of_replicas": 0
  	},
  	"mappings":{
  		"properties":{
  			"name":{
  				"type":"keyword"
  			},
  			"icon":{
  				"type":"text"
  			},
  			"age":{
  				"type":"long"
  			},
  			"id":{
  				"type":"text"
  			}
  		}
  	}
  }`
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
3.添加索引方法

新增数据时,应先判断是否存在索引

  // 添加文档
  func Addindex(table string) (bool, error) {
  	// 创建index前,先查看es引擎中是否存在自己想要创建的索引index
  	exists, err := EsClient.IndexExists(table).Do(ctx)
  	if err != nil {
  		fmt.Println("存在索引:", err)
  		return true, nil
  	}
  	if !exists {
  		// 如果不存在,就创建
  		createIndex, err := EsClient.CreateIndex(table).BodyString(mapping).Do(ctx)
  		if err != nil {
  			return false, err
  		}
  		if !createIndex.Acknowledged {
  			return false, err
  		}
  	}
  	return true, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
2.增加方法

说明: 增加数据时, 我们会先判断是否存在索引

(1). 新增一条
// 添加数据
  func Add(table string, data interface{}) (bool, error) {
  	// 添加索引
  	_, err := Addindex(table)
  	if err != nil {
  		log.Fatal("创建索引失败", err)
  	}
  	// 添加文档
  	res, err := EsClient.Index().
  		Index(table).
  		BodyJson(data).
  		Do(ctx)
  	if err != nil {
  		return false, err
  	}
  	fmt.Println("添加数据成功:", res)
  	return true, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
使用方法:
data := data{
    Id:   "1",
    Icon: "头像",
    Name: "名称",
    Age:  10,
}
res ,err := Add("test", data)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
(2). 批量新增
  func BulkAdd(table string, d []data) (bool, error) {
  	// 添加索引
  	_, err := Addindex("test")
  	if err != nil {
  		log.Fatal("创建索引失败", err)
  	}
  	bulkReq := EsClient.Bulk()
  	for _, v := range d {
  		req := elastic.NewBulkIndexRequest().
  			Index(table).
  			Doc(v)
  		bulkReq = bulkReq.Add(req)
  	}
  	res, err := bulkReq.Do(ctx)
  	if err != nil {
  		return false, err
  	}
  	fmt.Println("添加数据成功:", res)
  	return true, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
使用方法:
var d []interface{}
for i := 0;i < 100; i++ {
	iStr := strconv.Itoa(i)
	v := data{
		Id: iStr,
		Icon: "icon " + iStr,
		Name: "name " + iStr,
		Age: i,
	}
	d = append(d, v)
}
res ,err := BulkAdd("test", d)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
3.查询方法

sort 字段不能为text类型字段

  func Query(table string, field string, filter elastic.Query, sort string, page int, limit int) (*elastic.SearchResult, error) {
  	// 分页数据处理
  	isAsc := true
  	if sort != "" {
  		sortSlice := strings.Split(sort, " ")
  		sort = sortSlice[0]
  		if sortSlice[1] == "desc" {
  			isAsc = false
  		}
  	}
  	// 查询位置处理
  	if page <= 1 {
  		page = 1
  	}
  
  	fsc := elastic.NewFetchSourceContext(true)
  	// 返回字段处理
  	if field != "" {
  		fieldSlice := strings.Split(field, ",")
  		if len(fieldSlice) > 0 {
  			for _, v := range fieldSlice {
  				fsc.Include(v)
  			}
  		}
  	}
  
  	// 开始查询位置
  	fromStart := (page - 1) * limit
  	res, err := EsClient.Search().
  		Index(table).
  		FetchSourceContext(fsc).
  		Query(filter).
  		Sort(sort, isAsc).
  		From(fromStart).
  		Size(limit).
  		Pretty(true).
  		Do(ctx)
  	if err != nil {
  		return nil, err
  	}
  	return res, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
使用方法:
  // 精准查询
  //filter := elastic.NewTermQuery("name", "李白")

  // 分词匹配查询
  // match_all 查询所有
  filter := elastic.NewMatchAllQuery()
  // match 单个字符匹配
  // filter := elastic.NewMatchQuery("name", "渡汉江")
  // multi_match 多个字段进行匹配查询
  //filter := elastic.NewMultiMatchQuery("白日", "name", "icon")
  // match_phrase 短语匹配
  //filter := elastic.NewMatchPhraseQuery("icon", "途穷反遭俗眼白")

  // fuzzy模糊查询 fuzziness是可以允许纠正错误拼写的个数
  //filter := elastic.NewFuzzyQuery("icon", "夜").Fuzziness(1)

  // wildcard 通配符查询
  //filter := elastic.NewWildcardQuery("name", "静夜*")

  table := "test"
  sort := "age asc"
  page := 0
  limit := 10
  field := "name,icon,age"
  res, err := Query(table, field, filter, sort, page, limit)
  strD, _ := json.Marshal(res)
  fmt.Println(string(strD), err)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
4.修改方法
  func UpWhere(table string, filter elastic.Query, data map[string]interface{}) (bool, error) {
  	// 修改数据组装
  	if len(data) < 0 {
  		return false, errors.New("修改参数不正确")
  	}
  	scriptStr := ""
  	for k := range data {
  		scriptStr += "ctx._source." + k + " = params." + k + ";"
  	}
  	script := elastic.NewScript(scriptStr).Params(data)
  	res, err := EsClient.UpdateByQuery(table).
  		Query(filter).
  		Script(script).
  		Do(ctx)
  	if err != nil {
  		return false, err
  	}
  	fmt.Println("添加数据成功:", res)
  	return true, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
使用方法:
  table := "test"
  filter := elastic.NewTermQuery("name", "name 0")
  data := make(map[string]interface{})
  data["icon"] = "world10"
  data["age"] = 10
  res, err := UpWhere(table, filter, data)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
5.删除方法
  func Del(table string, filter elastic.Query) (bool, error) {
  	res, err := EsClient.DeleteByQuery().
  		Query(filter).
  		Index(table).
  		Do(ctx)
  	if err != nil {
  		return false, err
  	}
  	fmt.Println("删除信息:", res)
  	return true, nil
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
使用方法:
filter := elastic.NewTermQuery("name", "name 1")
res, err := Del("test", filter)
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/734094
推荐阅读
相关标签
  

闽ICP备14008679号