首页 > 其他分享 >elasticSearch配合go基本使用

elasticSearch配合go基本使用

时间:2023-03-16 21:22:39浏览次数:39  
标签:goods nil err fmt 配合 elasticSearch go gin model

一。连接

package model

import (
"fmt"

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

var EsClient *elastic.Client

func init() {
//注意IP和端口
EsClient, err = elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))

if err != nil {
fmt.Println(err)
}
}

二。基本指令
package _default

import (
"context"
"encoding/json"
"fmt"
"gin/model"
"github.com/gin-gonic/gin"
"github.com/olivere/elastic/v7"
"net/http"
"reflect"
"strconv"
)

//elasticsearch

type SearchController struct {
BaseController
}

// 初始化的时候判断goods是否存在 创建索引配置映射
func (con SearchController) Index(c *gin.Context) {
// Use the IndexExists service to check if a specified index exists.
exists, err := model.EsClient.IndexExists("goods").Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
print(exists)
if !exists {
// Create a new index.
mapping := `
{
"settings":{
"number_of_shards":1,
"number_of_replicas":0
},
"mappings":{
"properties": {
"Content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"Title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
}
`
//注意:增加的写法
_, err := model.EsClient.CreateIndex("goods").Body(mapping).Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
}

c.String(200, "创建索引配置映射成功")
}

// 增加商品数据
func (con SearchController) AddGoods(c *gin.Context) {
goods := []model.Goods{}
model.DB.Find(&goods)

for i := 0; i < len(goods); i++ {
_, err := model.EsClient.Index().
Index("goods").
Type("_doc").
Id(strconv.Itoa(goods[i].Id)).
BodyJson(goods[i]).
Do(context.Background())
if err != nil {
//Handle error
fmt.Println(err)
}
}
c.String(http.StatusOK, "AddGoods success")

}

// 更新数据
func (con SearchController) UpdateGoods(c *gin.Context) {
goods := []model.Goods{}
model.DB.Find(&goods)

goods[0].Title = "我是修改后的数据"
goods[0].GoodsContent = "我是修改后的数据GoodsContent"

_, err := model.EsClient.Update().
Index("goods").
Type("_doc").
Id("19").
Doc(goods[0]).
Do(context.Background())

if err != nil {
//Handle error
fmt.Println(err)
}

c.String(http.StatusOK, "修改数据 success")

}

// 删除数据
func (con SearchController) DeleteGoods(c *gin.Context) {
_, err := model.EsClient.Delete().
Index("goods").
Type("_doc").
Id("19").
Do(context.Background())

if err != nil {
//Handle error
fmt.Println(err)
}
c.String(http.StatusOK, "删除成功 success")
}

// 查询一条数据
func (con SearchController) GetOne(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recoverd in f", r)
c.String(http.StatusOK, "GetOne Error")
}
}()

result, err := model.EsClient.Get().
Index("goods").
Type("_doc").
Id("19").
Do(context.Background())

if err != nil {
panic(err)
}

goods := model.Goods{}
fmt.Printf("%#v", result.Source)
json.Unmarshal(result.Source, &goods)

c.JSON(http.StatusOK, gin.H{
"goods": goods,
})
}

// 自定义条件
func (con SearchController) Query(c *gin.Context) {

defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
c.String(200, "Query Error")
}
}()

query := elastic.NewMatchQuery("Title", "小米")
searchResult, err := model.EsClient.Search().
Index("goods"). // 设置索引名
Query(query).
Sort("Id", true). // 设置排序字段,根据 create_time 字段升序排序
From(0). // 设置分页参数 - 起始偏移量,从第 0 行记录开始
Size(10). // 设置分页参数 - 每页大小
Do(context.Background()) // 执行请求

if err != nil {
panic(err)
}

goods := model.Goods{}
c.JSON(200, gin.H{
"searchResult": searchResult.Each(reflect.TypeOf(goods)),
})
}

// 分页查询
func (con SearchController) PagingQuery(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recoverd in f", r)
c.String(http.StatusOK, "Query Error")
}
}()

page, _ := strconv.Atoi(c.Query("page"))
if page == 0 {
page = 1
}

pageSize := 2

query := elastic.NewMatchQuery("Title", "小米")
searchResult, err := model.EsClient.Search().
Index("goods").
Query(query).
Sort("Id", true).
From((page - 1) * pageSize).Size(pageSize).
Do(context.Background())

if err != nil {
panic(err)
}

goods := model.Goods{}
c.JSON(http.StatusOK, gin.H{
"searchResult": searchResult.Each(reflect.TypeOf(goods)),
})
}

// 条件赛选查询
func (con SearchController) FilterQuery(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recoverred in f", r)
c.String(http.StatusOK, "Query Error")
}
}()

//筛选
boolQ := elastic.NewBoolQuery()
boolQ.Must(elastic.NewMatchQuery("Title", "小米"))
boolQ.Filter(elastic.NewRangeQuery("Id").Gt(19))
boolQ.Filter(elastic.NewRangeQuery("Id").Lt(43))
searchResult, err := model.EsClient.Search().
Index("goods").
Type("_doc").
Query(boolQ).
Do(context.Background())

if err != nil {
fmt.Println(err)
}

goodsList := []model.Goods{}
var goods model.Goods
for _, item := range searchResult.Each(reflect.TypeOf(goods)) {
t := item.(model.Goods)
fmt.Printf("Id:%v 标题:%v\n", t.Id, t.Title)
goodsList = append(goodsList, t)
}

c.JSON(http.StatusOK, gin.H{
"goodsList": goodsList,
})
}

标签:goods,nil,err,fmt,配合,elasticSearch,go,gin,model
From: https://www.cnblogs.com/lunar-huazai/p/17224201.html

相关文章