不多说直接看代码吧
封装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) } }
请求参数
有疑问加站长微信联系(非本文作者)