- 創建搜索模型
package Models
const (
OrderByPriceAsc=1 //價格從低到高
OrderByPriceDesc=2 //價格從高到低
)
type SearchModel struct {
BookName string `json:"book_name" binding:"omitempty"`
BookPress string `json:"book_press" binding:"omitempty"`
BookPrice1Start float32 `json:"book_price1_start" binding:"gte=0,lt=10000"`
BookPrice1End float32 `json:"book_price1_end" binding:"gte=0,lt=10000,mygte=BookPrice1Start"`
OrderSet struct{
Score bool `json:"score" `
PriceOrder int `json:"price_order" binding:"oneof=0 1 2"`
} `json:"OrderSet" binding:"required,dive"`
Current int `json:"current" binding:"gte=1"`
Size int `json:"size" binding:"oneof=10 20 50"`
}
func NewSearchModel() *SearchModel {
return &SearchModel{}
}
- 搜索資料方法
package Funs
import (
"es.jtthink.com/AppInit"
"es.jtthink.com/Models"
"github.com/gin-gonic/gin"
"github.com/olivere/elastic/v7"
"log"
)
func SearchBook(ctx *gin.Context) {
searchModel:=Models.NewSearchModel()
//接收引數
err:=ctx.BindJSON(searchModel)
if err!=nil{
log.Println(err)
ctx.JSON(400,gin.H{"error":err.Error()})
return
}
//where陣列
qList:=make([]elastic.Query,0)
//加入圖書名搜索條件
if searchModel.BookName !="" {
machQuery:=elastic.NewMatchQuery("BookName",searchModel.BookName)
qList=append(qList,machQuery)
}
//加入出版社搜索條件
if searchModel.BookPress!="" { //判斷出版社
pressQuery:=elastic.NewTermQuery("BookPress",searchModel.BookPress)
qList=append(qList,pressQuery)
}
//價格搜索范圍
if searchModel.BookPrice1Start>0 || searchModel.BookPrice1End>0{
priceRangeQuery:=elastic.NewRangeQuery("BookPrice1")
if searchModel.BookPrice1Start>0{
priceRangeQuery.Gte(searchModel.BookPrice1Start)
}
if searchModel.BookPrice1End>0{
priceRangeQuery.Lte(searchModel.BookPrice1End)
}
qList=append(qList,priceRangeQuery)
}
//處理排序
sortList:=make([]elastic.Sorter,0)
{
if searchModel.OrderSet.Score{//以匹配度從高到低
sortList=append(sortList,elastic.NewScoreSort().Desc())
}
if searchModel.OrderSet.PriceOrder==Models.OrderByPriceAsc{ //以價格從低到高
sortList=append(sortList,elastic.NewFieldSort("BookPrice1").Asc())
}
if searchModel.OrderSet.PriceOrder==Models.OrderByPriceDesc{ //以價格從高到低
sortList=append(sortList,elastic.NewFieldSort("BookPrice1").Desc())
}
}
//must 相當于 where ... and ...
boolMustQuery:=elastic.NewBoolQuery().Must(qList...)
//分頁
rsp,err:=AppInit.GetEsClient().Search().Query(boolMustQuery).SortBy(sortList...).
From((searchModel.Current-1)*searchModel.Size).Size(searchModel.Size).
Index("books").Do(ctx)
log.Println(err)
if err!=nil{
ctx.JSON(500,gin.H{"error":err})
}else{
ctx.JSON(200,gin.H{"result":MapToBooks(rsp),"metas":gin.H{"total":rsp.TotalHits()}})
}
}
- 測驗

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/78140.html
標籤:其他
