不多說直接看代碼吧
封裝Search 查詢條件過濾
search.go
func Search(param map[string]interface{})(err,data [] elastic.Query){
var query [] elastic.Query
elastic.NewDateRangeAggregation()
if param["name"]!=nil{
query =append(query,elastic.NewMatchQuery("name", param["name"]))
}
//全文搜索
if param["searchkey"]!=nil{
query =append(query,elastic.NewMultiMatchQuery(param["searchkey"]).
Type("best_fields").
Lenient(true).
MinimumShouldMatch("30%"))
//.Analyzer("ik_smart"))
}
return err,query
}
getList 查詢數據
func GetList(index string ,info map[string]interface{},pagesize,pagestart int,searchcondition [] elastic.Query, sort string)(err error,ret interface{},total int64){
client, _ = elastic.NewClient(elastic.SetURL(host...))
boolQuery := elastic.NewBoolQuery()
boolQuery.Filter(searchcondition...)
//排序
isAsc := true
if sort != "" {
sortSlice := strings.Split(sort, " ")
sort = sortSlice[0]
if sortSlice[1] == "desc" {
isAsc = false
}
}
res, err := client.Search().
Index(index).
Query(boolQuery).
From(pagestart).
Size(pagesize).
Sort(sort, isAsc).
Pretty(true).
Do(context.Background())
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
return err,res.Hits.Hits, res.Hits.TotalHits.Value
}
引用
func GetList(c *gin.Context){
var pageInfo = make(map[string]interface{})
_ =c.ShouldBindJSON(&pageInfo)
order := ""
if pageInfo["order"] !=nil{
order = pageInfo["order"].(string)
}
//分頁
if pageInfo["pageSize"] ==nil{
pageInfo["pageSize"] =float64(10)
}
if pageInfo["page"] ==nil{
pageInfo["page"] =float64(1)
}
pagesize := int(pageInfo["pageSize"].(float64))
pagestart := int(pageInfo["pageSize"].(float64)) * (int(pageInfo["page"].(float64))-1)
_,search :=service.SearchTest(pageInfo)
if err,list,total :=service.GetList("test",pageInfo,pagesize,pagestart,search,order); err !=nil {
response.FailWithMessage(err.Error(),c)
}else{
response.OkWithDetailed(response.PageResult{
List: list,
Page: int(pageInfo["page"].(float64)),
Total: total,
PageSize:int(pageInfo["pageSize"].(float64)),
},"獲取成功",c)
}
}