golang 整合 es

安装

拉取es镜像

docker pull docker.elastic.co/elasticsearch/elasticsearch:7.12.0

创建docker容器

docker run --name elasticsearch -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.12.0

golang操作ES

创建连接对象

package main

import (
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.145:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)

}

func main() {
	ESconn()
}

创建索引

package main

import (
	"context"
	"log"
	"time"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       uint      `json:"id"`
	UserName string    `json:"user_name"`
	NickName string    `json:"nick_name"`
	CreareAt time.Time `json:"create_at"`
}

// 索引约束
func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}

// 删除索引
func DelIndex(index string) {
	coon.DeleteIndex(index).Do(context.Background())
}

// 创建索引
func CreateIndex() {
	exists, _ := IndexExists()
	if exists {
		log.Println("索引存在")
		DelIndex("user_index")
		CreateIndex()
	} else {
		log.Println("尝试创建索引")
		createIndex, err := coon.CreateIndex("user_index").BodyString(UserModel{}.Mapping()).Do(context.Background())
		if err != nil {
			log.Println(err)
			return
		}
		log.Println(createIndex)
		log.Println(createIndex.Index, "创建索引成功")
	}
}

// 判断索引是否存在
func IndexExists() (bool, error) {
	exists, err := coon.IndexExists("user_index").Do(context.Background())
	return exists, err
}

func main() {
	ESconn()
	CreateIndex()
}

添加文档

package main

import (
	"context"
	"log"
	"strconv"
	"time"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

// 创建文档
func AddDoc() {
	u := UserModel{
		Id:       1,
		UserName: "小明",
		NickName: "高大威猛 风流倜傥",
		CreareAt: time.Now().Format("2006-01-02 15:04:05"),
	}
	indexRes, err := coon.Index().Index(u.GetIndexName()).Id(strconv.Itoa(u.Id)).BodyJson(u).Do(context.Background())

	if err != nil {
		log.Println("添加失败")
	} else {
		log.Println("添加成功", indexRes)
	}

}

func main() {
	ESconn()
	AddDoc()
}

删除文档

package main

import (
	"context"
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

// 删除索引
func DelDocById() {
	res, err := coon.Delete().Index(UserModel{}.GetIndexName()).Id("1").Refresh("true").Do(context.Background())

	if err != nil {
		log.Println(err.Error())
	} else {
		log.Println("删除成功", res)
	}
}

func main() {
	ESconn()
	DelDocById()
}

文档查询

package main

import (
	"context"
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

func FindList() {
	query := elastic.NewBoolQuery()
	res, err := coon.Search(UserModel{}.GetIndexName()).Query(query).From(0).Size(10).Do(context.Background())
	if err != nil {
		log.Println(err)
		return
	} else {
		count := res.Hits.TotalHits.Value
		log.Println("查询到了数据总数", count)
		for _, hit := range res.Hits.Hits {

			log.Println(string(hit.Source))
		}
	}
}

func main() {
	ESconn()
	FindList()
}

精确匹配查询

精确匹配查询要求查询的字段必须是keyword类型

package main

import (
	"context"
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

// 精确匹配
func AccurateFindList() {
	query := elastic.NewTermQuery("user_name", "阿珍")
	res, err := coon.Search(UserModel{}.GetIndexName()).Query(query).From(0).Size(10).Do(context.Background())
	if err != nil {
		log.Println(err)
		return
	} else {
		count := res.Hits.TotalHits.Value
		log.Println("查询到了数据总数", count)
		for _, hit := range res.Hits.Hits {

			log.Println(string(hit.Source))
		}
	}
}

func main() {
	ESconn()
	AccurateFindList()
}

模糊匹配查询

主要用于搜索test类型

package main

import (
	"context"
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

// 模糊匹配
func VagueFindList() {
	query := elastic.NewMatchQuery("nick_name", "大豆")
	res, err := coon.Search(UserModel{}.GetIndexName()).Query(query).From(0).Size(10).Do(context.Background())
	if err != nil {
		log.Println(err)
		return
	} else {
		count := res.Hits.TotalHits.Value
		log.Println("查询到了数据总数", count)
		for _, hit := range res.Hits.Hits {
			log.Println(string(hit.Source))
		}
	}
}

func main() {
	ESconn()
	VagueFindList()
}

文档更新

package main

import (
	"context"
	"log"

	"github.com/olivere/elastic/v7"
)

// es连接对象
var coon *elastic.Client

// 连接es
func ESconn() {
	var err error
	coon, err = elastic.NewClient(
		elastic.SetURL("http://192.168.153.146:9200"),
		elastic.SetSniff(false),
	)

	if err != nil {
		log.Println("启动失败")
		return
	}
	log.Println(coon)
}

type UserModel struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	NickName string `json:"nick_name"`
	CreareAt string `json:"create_at"`
}

func (UserModel) Mapping() string {
	return `
		{
			"mappings": {
				"properties": {
					"nick_name": {
						"type": "text"
					},
					"user_name": {
						"type": "keyword"
					},
					"id": {
						"type": "integer"
					},
					"create_at": {
						"type": "date",
						"null_value": "null",
						"format": "[yyyy-MM-dd HH:mm:ss]"
					}
				}
			}
		}
	`
}
func (UserModel) GetIndexName() string {
	return "user_index"
}

// 模糊匹配
func UpDataDoc() {

	data := map[string]any{
		"nick_name": "更新后的值",
	}
	res, err := coon.Update().Index(UserModel{}.GetIndexName()).Id("2").Doc(data).Do(context.Background())

	if err != nil {
		log.Println(err)
		return
	} else {
		log.Println(res)
	}
}

func main() {
	ESconn()
	UpDataDoc()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值