From e189b1942c8130d473a1a4128c3d9ef5edfaa564 Mon Sep 17 00:00:00 2001 From: sunty <1172534965@qq.com> Date: 星期五, 23 十月 2020 10:58:30 +0800 Subject: [PATCH] fix --- EsApi.go | 1276 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 files changed, 1,175 insertions(+), 101 deletions(-) diff --git a/EsApi.go b/EsApi.go index 09cd5e7..96348c7 100644 --- a/EsApi.go +++ b/EsApi.go @@ -1,16 +1,26 @@ package esutil import ( + "basic.com/pubsub/protomsg.git" "encoding/json" "errors" "fmt" + "sort" "strconv" "strings" "sync" "time" - - "basic.com/pubsub/protomsg.git" ) + +var logPrint = func(i ...interface{}) { + fmt.Println(i) +} + +func InitLog(fn func(i ...interface{})) { + if fn != nil { + logPrint = fn + } +} // 鏍规嵁鎶撴媿浜哄憳id鏌ヨ鎶撴媿浜哄憳淇℃伅 func AIOceaninfosbyid(id []string, indexName string, serverIp string, serverPort string) ([]protomsg.AIOcean, error) { @@ -43,7 +53,6 @@ } aIOcean := AIOceanAnalysis(sources) - println(aIOcean) return aIOcean, nil } @@ -72,12 +81,778 @@ if err != nil { return "", err } + feature := sources[0]["targetInfo"].([]interface{})[0].(map[string]interface{})["feature"].(string) return feature, nil } +//鏍规嵁鐩爣id鏌ヨ宸茶拷鍔犳潯鏁� +func GetLinkTagInfoSize(id string, indexName string, serverIp string, serverPort string) (size int, err error) { + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + queryDSL := `{ + "query": { + "term":{ + "id":"` + id + `" + } + } + }` + buf, err := EsReq("POST", url, []byte(queryDSL)) + if err != nil { + return -1, err + } + source, err := Sourcelist(buf) + if err != nil { + return -1, err + } + if source[0]["linkTagInfo"] != nil { + size = len(source[0]["linkTagInfo"].([]interface{})) + } else { + return -1, errors.New("璇ユ暟缁勪笉瀛樺湪") + } + return size, nil +} + +//鏍规嵁鐩爣id杩藉姞璺熻釜淇℃伅 +func AppendTargetInfo(id string, targetInfo string, indexName string, serverIp string, serverPort string, updateTime string) (string, error) { + if targetInfo == "" { + return "", errors.New("append data is nil") + } + var info interface{} + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query?refresh=true" + jsonDSL := `{ + "query": { + "term":{ + "id":"` + id + `" + } + }, + "script": { + "lang": "painless", + "inline": "ctx._source.linkTagInfo.add(params.newparam);ctx._source.updateTime='` + updateTime + `'", + "params": { + "newparam": ` + targetInfo + ` + } + } +}` + logPrint(jsonDSL) + buf, err := EsReq("POST", url, []byte(jsonDSL)) + if err != nil { + return "", err + } + json.Unmarshal(buf, &info) + out, ok := info.(map[string]interface{}) + logPrint(out) + if !ok { + return "", errors.New("http response interface can not change map[string]interface{}") + } + middle, ok := out["updated"].(float64) + if !ok { + return "", errors.New("first updated change error!") + } + mes := "" + if middle == 1 { + mes = "杩藉姞鎴愬姛" + } + if middle == 0 { + mes = "宸茬粡杩藉姞" + } + return mes, nil + +} + +/**************************************customer analysis util start**************************************/ +/*******************sort []map util*******************/ +type MapsSort struct { + Key string + MapList []map[string]interface{} +} + +func (m *MapsSort) Len() int { + return len(m.MapList) +} + +func (m *MapsSort) Less(i, j int) bool { + return m.MapList[i][m.Key].(string) > m.MapList[j][m.Key].(string) +} + +func (m *MapsSort) Swap(i, j int) { + m.MapList[i], m.MapList[j] = m.MapList[j], m.MapList[i] +} + +/*******************sort []map util*******************/ +//鏍规嵁鏃堕棿鑼冨洿鑱氬悎鎵�鏈夊尯鍩熶汉淇℃伅锛岃繑鍥炲浐瀹氭潯鏁� +func GetFaceDataByTimeAndTotal(startTime string, endTime string, total int, thresholdTime int, thresholdStayTime int, serverIp string, serverPort string, indexName string) (resData []map[string]interface{}, err error) { + var requestUrl = "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + var requestBody = `{ + "query": { + "bool": { + "filter": [ + { + "range": { + "picDate": { + "gte": "` + startTime + `", + "lte": "` + endTime + `" + } + } + }, + { + "term":{ + "targetInfo.targetType.raw": "FaceDetect" + } + } + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "faceId": { + "terms": { + "field": "baseInfo.targetId" + } + } + }, + { + "areaId": { + "terms": { + "field": "targetInfo.areaId" + } + } + } + ], + "size": 10000000 + }, + "aggs": { + "top_attention_hits": { + "top_hits": { + "size": 1000000, + "sort": [ + { + "picDate": { + "order": "asc" + } + } + ], + "_source": { + "includes": [ + "baseInfo.targetId", + "targetInfo.picSmUrl", + "targetInfo.areaId", + "picDate" + ] + } + } + } + } + } + } +}` + buf, err := EsReq("POST", requestUrl, []byte(requestBody)) + if err != nil { + return nil, err + } + source, err := FaceSourceAggregations(buf, thresholdTime, thresholdStayTime) + if err != nil { + return nil, err + } + if len(source) == 0 { + return source, nil + } + faceSource := make([]map[string]interface{}, 0) + for index, info := range source { + if int(info["stayTime"].(float64)) > thresholdStayTime { + faceSource = append(faceSource, source[index]) + } + } + mapsSort := MapsSort{} + mapsSort.Key = "endTime" + mapsSort.MapList = faceSource + sort.Sort(&mapsSort) + if len(faceSource) > total { + return mapsSort.MapList[:total], nil + } + return mapsSort.MapList, nil +} + +func GetFaceDataByTimeAndId(startTime string, endTime string, id string, thresholdTime int, thresholdStayTime int, serverIp string, serverPort string, indexName string) (resData []map[string]interface{}, err error) { + var requestUrl = "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + var requestBody = `{ + "query": { + "bool": { + "filter": [ + { + "range": { + "picDate": { + "gte": "` + startTime + `", + "lte": "` + endTime + `" + } + } + }, + { + "term":{ + "targetInfo.targetType.raw": "FaceDetect" + } + }, + { + "term":{ + "baseInfo.targetId": "` + id + `" + } + } + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "faceId": { + "terms": { + "field": "baseInfo.targetId" + } + } + }, + { + "areaId": { + "terms": { + "field": "targetInfo.areaId" + } + } + } + ], + "size": 10000000 + }, + "aggs": { + "top_attention_hits": { + "top_hits": { + "size": 1000000, + "sort": [ + { + "picDate": { + "order": "asc" + } + } + ], + "_source": { + "includes": [ + "baseInfo.targetId", + "targetInfo.picSmUrl", + "targetInfo.areaId", + "picDate" + ] + } + } + } + } + } + } +}` + buf, err := EsReq("POST", requestUrl, []byte(requestBody)) + if err != nil { + return nil, err + } + source, err := FaceSourceAggregations(buf, thresholdTime, thresholdStayTime) + if err != nil { + return nil, err + } + if len(source) == 0 { + return source, nil + } + faceSource := make([]map[string]interface{}, 0) + for index, info := range source { + if int(info["stayTime"].(float64)) > thresholdStayTime { + faceSource = append(faceSource, source[index]) + } + } + mapsSort := MapsSort{} + mapsSort.Key = "startTime" + mapsSort.MapList = faceSource + sort.Sort(&mapsSort) + return mapsSort.MapList, nil +} + +func GetFaceIdDeduplication(startTime string, endTime string, serverIp string, serverPort string, indexName string) (ids []map[string]interface{}, err error) { + var requestUrl = "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + var requestBody = `{ + "query": { + "bool": { + "filter": [ + { + "range": { + "picDate": { + "gte": "` + startTime + `", + "lte": "` + endTime + `" + } + } + }, + { + "term": { + "targetInfo.targetType.raw": "FaceDetect" + } + } + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "faceId": { + "terms": { + "field": "baseInfo.targetId" + } + } + } + ], + "size": 10000000 + }, + "aggs": { + "top_attention_hits": { + "top_hits": { + "size": 1, + "sort": [ + { + "picDate": { + "order": "desc" + } + } + ], + "_source": { + "includes": [ + "picDate" + ] + } + } + } + } + } + } + } +}` + //fmt.Println(requestUrl) + //fmt.Println(requestBody) + buf, err := EsReq("POST", requestUrl, []byte(requestBody)) + if err != nil { + return nil, err + } + ids, err1 := SourceDeduplication(buf) + if err1 != nil { + return nil, err1 + } + if len(ids) > 1 { + mapsSort := MapsSort{} + mapsSort.Key = "lastTime" + mapsSort.MapList = ids + sort.Sort(&mapsSort) + return mapsSort.MapList, nil + } + return ids, nil +} + +//缁熻鍚勪釜鍖哄煙浜烘暟 +func StatisticsEveryAreaPersonsNumber(startTime string, endTime string, serverIp string, serverPort string, indexName string) ([]map[string]interface{}, error) { + var requestUrl = "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + var requestBody = `{ + "query": { + "bool": { + "filter": [ + { + "range": { + "picDate": { + "gte": "` + startTime + `", + "lte": "` + endTime + `" + } + } + }, + { + "term": { + "targetInfo.targetType.raw": "Yolo" + } + } + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "areaId": { + "terms": { + "field": "targetInfo.areaId" + } + } + } + ], + "size": 10000000 + } + } + } +}` + buf, err := EsReq("POST", requestUrl, []byte(requestBody)) + if err != nil { + return nil, err + } + result, err := SourceStatistics(buf) + if err != nil { + return nil, err + } + return result, nil +} + +/**************************************customer analysis util end**************************************/ +//鏍规嵁鎽勫儚鏈哄垪琛ㄥ拰鏃堕棿鏌ヨ浜哄憳娴忚杞ㄨ抗 +func GetPersonDataByCameraIdAndTime(cameraId []string, startTime string, endTime string, serverIp string, serverPort string, indexName string) (map[string]interface{}, error) { + + var filterArr []string + if cameraId != nil && len(cameraId) > 0 { + esCameraId := strings.Replace(strings.Trim(fmt.Sprint(cameraId), "[]"), " ", "\",\"", -1) + filterArr = append(filterArr, `{ + "terms": { + "cameraId": ["`+esCameraId+`"] + } + }`) + } + filterArr = append(filterArr, `{ + "range": { + "picDate": { + "gte": "`+startTime+`", + "lte": "`+endTime+`" + } + } + }`) + filterArr = append(filterArr, ` { + "term": { + "targetInfo.targetType.raw": "Yolo" + } + }`) + queryStr := strings.Join(filterArr, ",") + + personUrl := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + personBody := `{ + "query": { + "bool": { + "filter": [ + ` + queryStr + ` + ] + } + }, + "size": 2147483647, + "_source": { + "includes": [ + "cameraId", + "cameraName", + "cameraAddr", + "targetInfo.targetScore", + "picDate", + "updateTime", + "picMaxUrl", + "targetInfo.belongsTargetId", + "targetInfo.targetLocation", + "picWH" + ] + } +}` + //fmt.Println(personUrl) + //fmt.Println(personBody) + source := make(map[string]interface{}) + queryStartTime := time.Now() + buf, err := EsReq("POST", personUrl, []byte(personBody)) + if err != nil { + return nil, err + } + queryUseTime := time.Now().Sub(queryStartTime).Seconds() * 1000 + sources, err := Sourcelist(buf) + if err != nil { + return nil, err + } + resData, err := PerSonAnalysis(sources) + source["result"] = resData + source["total"] = len(resData) + source["queryUseTime"] = queryUseTime + //println(sources) + return source, nil + +} + +//鏍规嵁鏃堕棿鑼冨洿锛屾憚鍍忔満鍒楄〃锛屽垎缁勮仛鍚堜汉鑴稿垪琛�,杩斿洖鍒嗙粍鏁版嵁 +func GetFaceDataBucketsByCameraIdAndTimeReturnByGrouped(cameraId []string, personId []string, startTime string, endTime string, thresholdTime float64, serverIp string, ServerPort string, indexName string) (buckersDate map[string]interface{}, err error) { + var filterArr []string + if cameraId != nil && len(cameraId) > 0 { + esCameraId := strings.Replace(strings.Trim(fmt.Sprint(cameraId), "[]"), " ", "\",\"", -1) + filterArr = append(filterArr, `{ + "terms": { + "cameraId": ["`+esCameraId+`"] + } + }`) + } + if personId != nil && len(personId) > 0 { + esPersonId := strings.Replace(strings.Trim(fmt.Sprint(personId), "[]"), " ", "\",\"", -1) + filterArr = append(filterArr, `{ + "terms": { + "baseInfo.targetId": ["`+esPersonId+`"] + } + }`) + } + filterArr = append(filterArr, `{ + "range": { + "picDate": { + "gte": "`+startTime+`", + "lte": "`+endTime+`" + } + } + }`) + filterArr = append(filterArr, ` { + "term": { + "targetInfo.targetType.raw": "FaceDetect" + } + }`) + queryStr := strings.Join(filterArr, ",") + + var buckersUrl = "http://" + serverIp + ":" + ServerPort + "/" + indexName + "/_search" + var buckersBody = `{ + "query": { + "bool": { + "filter": [ + ` + queryStr + ` + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "baseInfo.targetId": { + "terms": { + "field": "baseInfo.targetId" + } + } + }, + { + "cameraId": { + "terms": { + "field": "cameraId" + } + } + } + ], + "size": 10000000 + }, + "aggs":{ + "top_attention_hits":{ + "top_hits":{ + "size": 1000000, + "sort": [ + { + "picDate": { + "order": "asc" + } + } + ], + "_source":{ + "includes":["baseInfo.targetId","cameraId","cameraName","cameraAddr","targetInfo.targetScore","targetInfo.picSmUrl","showLabels","baseInfo.tableId","baseInfo.tableName","baseInfo.bwType","baseInfo.targetName","baseInfo.compareScore","picDate","picMaxUrl","picWH"] + } + } + } + } + } + } +}` + //fmt.Println(buckersUrl) + //fmt.Println(buckersBody) + sources := make(map[string]interface{}) + queryStartTime := time.Now() + buf, err := EsReq("POST", buckersUrl, []byte(buckersBody)) + if err != nil { + return nil, err + } + queryUseTime := time.Now().Sub(queryStartTime).Seconds() * 1000 + //fmt.Println(queryUseTime) + tmpSources, err := SourceAggregationsReturnByGrouped(buf, thresholdTime) + if err != nil { + return nil, err + } + sources["result"] = tmpSources + sources["total"] = len(tmpSources) + sources["queryUseTime"] = queryUseTime + //println(sources) + return sources, nil +} + +//鏍规嵁鏃堕棿鑼冨洿锛屾憚鍍忔満鍒楄〃锛屽垎缁勮仛鍚堜汉鑴稿垪琛� +func GetFaceDataBucketsByCameraIdAndTime(cameraId []string, personId []string, startTime string, endTime string, thresholdTime float64, serverIp string, ServerPort string, indexName string) (buckersDate map[string]interface{}, err error) { + var filterArr []string + if cameraId != nil && len(cameraId) > 0 { + esCameraId := strings.Replace(strings.Trim(fmt.Sprint(cameraId), "[]"), " ", "\",\"", -1) + filterArr = append(filterArr, `{ + "terms": { + "cameraId": ["`+esCameraId+`"] + } + }`) + } + if personId != nil && len(personId) > 0 { + esPersonId := strings.Replace(strings.Trim(fmt.Sprint(personId), "[]"), " ", "\",\"", -1) + filterArr = append(filterArr, `{ + "terms": { + "baseInfo.targetId": ["`+esPersonId+`"] + } + }`) + } + filterArr = append(filterArr, `{ + "range": { + "picDate": { + "gte": "`+startTime+`", + "lte": "`+endTime+`" + } + } + }`) + filterArr = append(filterArr, ` { + "term": { + "targetInfo.targetType.raw": "FaceDetect" + } + }`) + queryStr := strings.Join(filterArr, ",") + + var buckersUrl = "http://" + serverIp + ":" + ServerPort + "/" + indexName + "/_search" + var buckersBody = `{ + "query": { + "bool": { + "filter": [ + ` + queryStr + ` + ] + } + }, + "size": 0, + "aggs": { + "buckets_aggs": { + "composite": { + "sources": [ + { + "baseInfo.targetId": { + "terms": { + "field": "baseInfo.targetId" + } + } + }, + { + "cameraId": { + "terms": { + "field": "cameraId" + } + } + } + ], + "size": 10000000 + }, + "aggs":{ + "top_attention_hits":{ + "top_hits":{ + "size": 1000000, + "sort": [ + { + "picDate": { + "order": "asc" + } + } + ], + "_source":{ + "includes":["baseInfo.targetId","cameraId","cameraName","cameraAddr","targetInfo.targetScore","targetInfo.picSmUrl","showLabels","baseInfo.tableId","baseInfo.tableName","baseInfo.bwType","baseInfo.targetName","baseInfo.compareScore","picDate","picMaxUrl","picWH"] + } + } + } + } + } + } +}` + //fmt.Println(buckersUrl) + //fmt.Println(buckersBody) + queryStartTime := time.Now() + buf, err := EsReq("POST", buckersUrl, []byte(buckersBody)) + if err != nil { + return nil, err + } + queryUseTime := time.Now().Sub(queryStartTime).Seconds() * 1000 + + sources, err := SourceAggregations(buf, thresholdTime, queryUseTime) + if err != nil { + return nil, err + } + return sources, nil +} + +//鏍规嵁鎶撴媿浜哄憳id鏇存柊锛坧icurl锛夊浘鐗囧湴鍧� +func UpdatePicUrlById(id string, picUrl string, indexName string, serverIp string, serverPort string) (err error) { + updateTime := time.Now().Format("2006-01-02 15:04:05") + tRes, err := AIOceaninfosbyid([]string{id}, indexName, serverIp, serverPort) + if err != nil || len(tRes) == 0 { + return err + } + picMaxUrls := tRes[0].PicMaxUrl + sourceStr := ` + "source": "ctx._source.picMaxUrl.add('` + picUrl + `');ctx._source.updateTime='` + updateTime + `'" +` + if len(picMaxUrls) >= 2 { + sourceStr = `"source": "ctx._source.picMaxUrl[1]='` + picUrl + `';ctx._source.updateTime='` + updateTime + `'"` + } + var info interface{} + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query?refresh=true" + + var picUrlInfo = ` + { + "script": { + ` + sourceStr + ` + }, + "query": { + "bool": { + "filter": [ + { + "term": { + "id": "` + id + `" + } + } + ] + } + } + } + ` + //logPrint("url: ", url, videoUrlInfo) + //fmt.Println(url, picUrlInfo) + buf, err := EsReq("POST", url, []byte(picUrlInfo)) + if err != nil { + logPrint("http request videoUrlInfo info is err!") + return err + } + json.Unmarshal(buf, &info) + //logPrint(info) + out, ok := info.(map[string]interface{}) + if !ok { + logPrint("http response interface can not change map[string]interface{}") + return errors.New("http response interface can not change map[string]interface{}") + } + middle, ok := out["updated"].(float64) + if !ok { + logPrint("first updated change error!", out) + return errors.New("first updated change error!") + } + if middle == 1 { + return nil + } + if middle == 0 { + return errors.New("宸茬粡淇敼") + } + return nil +} + //鏍规嵁鎶撴媿浜哄憳id鏇存柊锛坴ideourl锛夋憚鍍忔満鍦板潃 -func UpdateVideourlById(id string, videoUrl string, indexName string, serverIp string, serverPort string, command int) (statu int) { +func UpdateVideourlById(id string, videoUrl string, indexName string, serverIp string, serverPort string, command int) (statu int, err error) { var info interface{} url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query?refresh=true" @@ -97,39 +872,39 @@ } } ` - //fmt.Println("url: ", url, videoUrlInfo) + //logPrint("url: ", url, videoUrlInfo) buf, err := EsReq("POST", url, []byte(videoUrlInfo)) if err != nil { - fmt.Println("http request videoUrlInfo info is err!") + logPrint("http request videoUrlInfo info is err!") statu = 500 - return + return statu, err } json.Unmarshal(buf, &info) - //fmt.Println(info) + //logPrint(info) out, ok := info.(map[string]interface{}) if !ok { - fmt.Println("http response interface can not change map[string]interface{}") + logPrint("http response interface can not change map[string]interface{}") statu = 500 - return + return statu, errors.New("http response interface can not change map[string]interface{}") } middle, ok := out["updated"].(float64) if !ok { - fmt.Println("first updated change error!") + logPrint("first updated change error!") statu = 500 - return + return statu, errors.New("first updated change error!") } if middle == 1 { statu = 200 - return + return statu, nil } if middle == 0 { statu = 201 - return + return statu, errors.New("宸茬粡淇敼") } - return statu + return statu, nil } -//鑾峰彇褰撳墠鑺傜偣鎶撴媿搴撴墍鏈変汉鍛業D +//鑾峰彇褰撳墠鑺傜偣鎶撴媿搴撴墍鏈変汉鍛業D*缂撳瓨* func GetAllLocalVideopersonsId(compareArgs protomsg.CompareArgs, indexName string, serverIp string, serverPort string, alarmLevelTypes string) (capturetable []string) { queryStr := "" queryBody := compareArgs.InputValue @@ -201,7 +976,7 @@ "\"size\":\"1000\"," + "\"query\":{\"bool\":{" + queryStr + "\"filter\":[" + - "{\"term\":{\"targetInfo.targetType.raw\":\"face\"}}," + + "{\"term\":{\"targetInfo.targetType.raw\":\"FaceDetect\"}}," + cameraIdStr + alarmLevelStr + taskIdStr + @@ -215,20 +990,20 @@ go func(reqParam string) { defer wg.Done() - //fmt.Println(url) - //fmt.Println(prama) + logPrint(url) + logPrint(prama) buf, err := EsReq("POST", url, []byte(reqParam)) if err != nil { - fmt.Println("http request videoUrlInfo info is err!") - fmt.Println(len(capturetable)) + logPrint("http request videoUrlInfo info is err!") + logPrint(len(capturetable)) return } sources, err := Sourcelistforscroll(buf) if err != nil { - fmt.Println(len(capturetable)) + logPrint(len(capturetable)) return } for _, source := range sources["sourcelist"].([]map[string]interface{}) { @@ -252,12 +1027,12 @@ "scroll": "1m", "scroll_id" : "` + scroll_id + `" }` - //fmt.Println(scroll_url) - //fmt.Println(jsonDSL) + logPrint(scroll_url) + logPrint(jsonDSL) buf, err := EsReq("POST", scroll_url, []byte(jsonDSL)) if err != nil { - fmt.Println("lenth1: ", len(capturetable)) + logPrint("lenth1: ", len(capturetable)) return } nextSources, err := Sourcelistforscroll(buf) @@ -267,16 +1042,16 @@ } nextM := nextSources["sourcelist"].([]map[string]interface{}) - //fmt.Println("id",nextSources) + //logPrint("id",nextSources) if nextM == nil || len(nextM) == 0 { - //fmt.Println("lenth: ", len(capturetable)) + //logPrint("lenth: ", len(capturetable)) return } - //fmt.Println("id") + //logPrint("id") for _, source := range nextM { tmpList = append(tmpList, source["id"].(string)) } - //fmt.Println("tmpList: ", len(tmpList)) + //logPrint("tmpList: ", len(tmpList)) lock.Lock() capturetable = append(capturetable, tmpList...) lock.Unlock() @@ -288,8 +1063,8 @@ } wg.Wait() - fmt.Println("lenth_all: ", len(capturetable)) - fmt.Println("鑰楁椂锛�", time.Since(ts)) + logPrint("lenth_all: ", len(capturetable)) + logPrint("鑰楁椂锛�", time.Since(ts)) return capturetable } @@ -298,33 +1073,28 @@ var aIOceanInfo []protomsg.AIOcean url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" - isAlarmStr := "" + var filterArr []string if isAlarm != "all" { - isAlarmStr = ` { + filterArr = append(filterArr, ` { "term":{ - "isAlarm":"` + isAlarm + `" + "isAlarm":"`+isAlarm+`" } - }` - + }`) } - categoryStr := "" if category != "all" { - categoryStr = ` { + filterArr = append(filterArr, ` { "term":{ - "targetInfo.targetType":"` + category + `" + "targetInfo.targetType.raw":"`+category+`" } - }` + }`) } - if categoryStr != "" && isAlarmStr != "" { - isAlarmStr = isAlarmStr+"," - } - queryStr := `"query":{ + + queryStr := `"query":{ "bool":{ "filter":[ - ` + isAlarmStr + ` - ` + categoryStr + ` + ` + strings.Join(filterArr, ",") + ` ] } },` @@ -335,7 +1105,7 @@ "sort":[{"picDate":{"order":"desc"}}], "_source": {"includes":[],"excludes":["*.feature"]} }` - fmt.Println(DSLJson) + //logPrint(DSLJson) buf, err := EsReq("POST", url, []byte(DSLJson)) if err != nil { return aIOceanInfo, err @@ -347,7 +1117,7 @@ } aIOcean := AIOceanAnalysis(sources) - //fmt.Println(len(videoperson)) + //logPrint(len(videoperson)) return aIOcean, nil } @@ -391,7 +1161,7 @@ } aIOcean := AIOceanAnalysis(sources) - fmt.Println(len(aIOcean)) + logPrint(len(aIOcean)) return aIOcean, nil } @@ -405,7 +1175,7 @@ "term":{ "isAlarm":"` + isAlarm + `" } - }` + },` } DSLJson := `{ @@ -425,7 +1195,6 @@ } } }` - //fmt.Println(DSLJson) buf, err := EsReq("POST", url, []byte(DSLJson)) if err != nil { return total, err @@ -441,7 +1210,7 @@ return total, errors.New("first hits change error!") } total = int(middle["total"].(float64)) - //fmt.Println(total) + //logPrint(total) return total, nil } @@ -463,9 +1232,9 @@ } }, "aggs":{ - "sdkName_status":{ + "taskName_status":{ "terms":{ - "field":"sdkName.raw" + "field":"taskName.raw" } } } @@ -484,16 +1253,16 @@ if !ok { return nil, errors.New("first hits change error!") } - sdkName_status, ok := middle["sdkName_status"].(map[string]interface{}) + sdkName_status, ok := middle["taskName_status"].(map[string]interface{}) if !ok { return nil, errors.New("first hits change error!") } - + //fmt.Println(sdkName_status) for _, in := range sdkName_status["buckets"].([]interface{}) { var source = make(map[string]interface{}, 0) tmpbuf, ok := in.(map[string]interface{}) if !ok { - fmt.Println("change to source error!") + logPrint("change to source error!") continue } sdkName := tmpbuf["key"].(string) @@ -502,7 +1271,7 @@ source["value"] = count sources = append(sources, source) } - //fmt.Println("tmpSource",sources) + //logPrint("tmpSource",sources) return sources, nil } @@ -575,7 +1344,7 @@ var source = make(map[string]interface{}, 0) tmpbuf, ok := in.(map[string]interface{}) if !ok { - fmt.Println("change to source error!") + logPrint("change to source error!") continue } task := tmpbuf["key"].(map[string]interface{}) @@ -587,28 +1356,33 @@ source["count"] = count sources = append(sources, source) } - //fmt.Println("tmpSource",sources) + //logPrint("tmpSource",sources) return sources, nil } +//娣诲姞鍗冲皢鍒犻櫎淇″彿 +func AddDeleteSignal() { + +} + /****************************************浠ヤ笅涓簊dkCompare姣斿缂撳瓨浣跨敤鏂规硶*********************************************/ -//鑾峰彇鏌ヨ鎬绘暟 -func GetTotal(serverIp string, serverPort string, indexName string, shards string) (total int) { +//鑾峰彇鏌ヨ鎬绘暟 *缂撳瓨* +func GetTotal(serverIp string, serverPort string, indexName string, shards string, targetType string) (total int) { JsonDSL := `{ "size": 0, "query": { "bool": { "filter": [{ "term": { - "targetInfo.targetType.raw": "face" + "targetInfo.targetType.raw": "` + targetType + `" } }] } } }` - url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search?preference=_shards:" + shards + "|_only_local" buf, err := EsReq("POST", url, []byte(JsonDSL)) if err != nil { return @@ -628,11 +1402,17 @@ } -//鏌ヨ鏃堕棿娈垫暟鎹� -func GetPeriodInfos(serverIp string, serverPort string, startTime string, endTime string, indexName string, shards string) ([]*protomsg.Esinfo, error) { - var capdbinfo []*protomsg.Esinfo +//鏌ヨ鏃堕棿娈垫暟鎹� *缂撳瓨* +func GetPeriodInfos(serverIp string, serverPort string, startTime string, endTime string, indexName string, shards string, targetType string) ([]*protomsg.MultiFeaCache, error) { + var capdbinfo []*protomsg.MultiFeaCache url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search?preference=_shards:" + shards + "|_only_local" - + var source []string + switch targetType { + case "face", "FaceDetect": + source = []string{"id", "targetInfo.feature", "analyServerId", "cameraId"} + case "track": + source = []string{"id", "targetInfo.feature", "analyServerId", "cameraId", "targetInfo.attachTarget.feature", "targetInfo.targetLocation", "linkTagInfo.targetInfo.feature", "linkTagInfo.targetInfo.attachTarget.feature", "linkTagInfo.cameraId", "linkTagInfo.targetInfo.targetLocation"} + } JsonDSL := ` { "query": { @@ -640,7 +1420,7 @@ "filter": [ { "term": { - "targetInfo.targetType.raw": "face" + "targetInfo.targetType.raw": "` + targetType + `" } }, { @@ -655,15 +1435,12 @@ } }, "size": 1000000, - "_source": [ - "id", - "targetInfo.feature", - "analyServerId" - ] + "_source": ["` + strings.Replace(strings.Trim(fmt.Sprint(source), "[]"), " ", "\",\"", -1) + `"] } ` //logger.Debug(url) //logger.Debug(JsonDSL) + //logPrint(JsonDSL) buf, err := EsReq("POST", url, []byte(JsonDSL)) if err != nil { return capdbinfo, errors.New("http request dbtablename info is err!") @@ -674,53 +1451,350 @@ if err != nil { return capdbinfo, err } - + //logPrint(sources) // 杩斿洖鎵�鏈夋煡璇㈢殑鏁版嵁 capdbinfos := Parsesources(sources) return capdbinfos, nil - } -// 鏌ヨ搴曞簱浜哄憳淇℃伅 -func GetOceanFeatures(serverIp string, serverPort string, queryIndexNum int, queryNums int, indexName string, shards string) ([]*protomsg.Esinfo, error) { - var dbinfos []*protomsg.Esinfo - point := strconv.Itoa(queryIndexNum) - number := strconv.Itoa(queryNums) +// 鏌ヨ搴曞簱浜哄憳淇℃伅*缂撳瓨* +func GetOceanFeatures(serverIp string, serverPort string, queryNums int, indexName string, shards string, targetType string) ([]*protomsg.MultiFeaCache, error) { + //queryIndexNum int + //var dbinfos []*protomsg.MultiFeaCache + dbinfos := make([]*protomsg.MultiFeaCache, 0) + //dbinfosss := make([]*protomsg.MultiFeaCache,0) + //dbinfoss = append(dbinfoss, dbinfosss...) + JsonDSL := "" - url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search?preference=_shards:" + shards + "|_only_local" - JsonDSL = ` { - "from": ` + point + `, + var source []string + switch targetType { + case "face", "FaceDetect": + source = []string{"id", "targetInfo.feature", "analyServerId"} + case "track": + source = []string{"id", "targetInfo.feature", "analyServerId", "targetInfo.attachTarget.feature", "targetInfo.targetLocation", "linkTagInfo.targetInfo.feature", "linkTagInfo.targetInfo.attachTarget.feature", "linkTagInfo.targetInfo.targetLocation"} + } + + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search?preference=_shards:" + shards + "|_only_local;scroll=1m" + + var lock sync.RWMutex + var wg sync.WaitGroup + + for i := 0; i < 48; i++ { + //璇锋眰浣� + JsonDSL = ` { + "slice": { + "id": "` + strconv.Itoa(i) + `", + "max": 48 + }, + "size":` + strconv.Itoa(queryNums) + `, "query": { "bool": { "filter": [ { "term": { - "targetInfo.targetType.raw": "face" + "targetInfo.targetType.raw": "` + targetType + `" } } ] } }, - "size":` + number + `, - "_source": [ - "id", - "targetInfo.feature", - "analyServerId" - ] + "_source": ["` + strings.Replace(strings.Trim(fmt.Sprint(source), "[]"), " ", "\",\"", -1) + `"] }` + wg.Add(1) + go func(reqJsonDSL string) { + defer wg.Done() - buf, err := EsReq("POST", url, []byte(JsonDSL)) - if err != nil { - return dbinfos, errors.New("http request dbtablename info is err!") + //fmt.Println(url) + //fmt.Println(prama) + //logPrint("url: ",url) + //logPrint("url: ",reqJsonDSL) + buf, err := EsReq("POST", url, []byte(reqJsonDSL)) + if err != nil { + logPrint("EsReq: ", err) + return + } + + // 杩斿洖 _source 鏁扮粍 + sources, err := Sourcelistforscroll(buf) + if err != nil { + logPrint("EsReq: ", err) + return + } + // 杩斿洖鎵�鏈夋煡璇㈢殑鏁版嵁 + ftmpDatas := Parsesources(sources["sourcelist"].([]map[string]interface{})) + lock.Lock() + dbinfos = append(dbinfos, ftmpDatas...) + //logPrint("prsLen: ", len(Parsesources(sources["sourcelist"].([]map[string]interface{})))) + //logPrint("dbinfosLen: ", len(dbinfos)) + lock.Unlock() + + scroll_id := sources["scroll_id"].(string) + + //scroll璇锋眰澶� + scroll_url := "http://" + serverIp + ":" + serverPort + "/_search/scroll" + for { + next_scroll_id := "" + if next_scroll_id != "" { + scroll_id = next_scroll_id + } + jsonDSL := `{ + "scroll": "1m", + "scroll_id" : "` + scroll_id + `" + }` + //fmt.Println(scroll_url) + //fmt.Println(jsonDSL) + buf, err := EsReq("POST", scroll_url, []byte(jsonDSL)) + + if err != nil { + //fmt.Println("lenth1: ", len(dbinfos)) + return + } + nextSources, err := Sourcelistforscroll(buf) + + if nextSources == nil { + return + } + + nextM := nextSources["sourcelist"].([]map[string]interface{}) + //fmt.Println("id",nextSources) + if nextM == nil || len(nextM) == 0 { + //fmt.Println("lenth: ", len(capturetable)) + return + } + tmpDatas := Parsesources(nextM) + lock.Lock() + dbinfos = append(dbinfos, tmpDatas...) + //logPrint("tmpDatasLen: ", len(tmpDatas)) + //logPrint("AdbinfosLen: ", len(dbinfos)) + lock.Unlock() + + next_scroll_id = nextSources["scroll_id"].(string) + } + + }(JsonDSL) } + wg.Wait() - // 杩斿洖 _source 鏁扮粍 - sources, err := Sourcelist(buf) - if err != nil { - return dbinfos, err + //fmt.Println("lenth_all: ", len(dbinfos)) + + return dbinfos, nil +} + +//************************CORN TASK******************************* +//鏌ヨ鏃ユ湡鑼冨洿鍐呮槸鍚﹁繕瀛樺湪鏁版嵁 +func QueryAnalyServerData(serverIp string, serverPort string, indexName string, startTime string, endTime string, analyServerId string) (result bool, err error) { + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search" + deleteJson := `{ + "query":{ + "bool":{ + "filter":[{ + "range":{ + "updateTime":{ + "gte":"` + startTime + `", + "lte":"` + endTime + `" + } + } + }, + { + "term":{ + "analyServerId":"` + analyServerId + `" + } + } + ] + } } +} ` + buf, err := EsReq("POST", url, []byte(deleteJson)) + if err != nil { + return false, errors.New("璇锋眰澶辫触") + } + resTotal, err := SourceTotal(buf) + if err != nil { + return false, errors.New("瑙g爜澶辫触") + } + if resTotal == -1 || resTotal == 0 { + result = false + } else { + result = true + } + return result, nil +} - // 杩斿洖鎵�鏈夋煡璇㈢殑鏁版嵁 - dbpersoninfos := Parsesources(sources) - return dbpersoninfos, nil +//鎸夋棩鏈熻寖鍥达紝鏈嶅姟鍣↖d鍒犻櫎鏁版嵁 +func DeleteAnalyServerData(serverIp string, serverPort string, indexName string, startTime string, endTime string, analyServerId string) (result bool, err error) { + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_delete_by_query" + deleteJson := `{ + "query":{ + "bool":{ + "filter":[{ + "range":{ + "updateTime":{ + "gte":"` + startTime + `", + "lte":"` + endTime + `" + } + } + }, + { + "term":{ + "analyServerId":"` + analyServerId + `" + } + } + ] + } + } +} ` + buf, err := EsReq("POST", url, []byte(deleteJson)) + if err != nil { + return false, errors.New("璇锋眰澶辫触") + } + deleteRes, err := SourceDeleted(buf) + if err != nil { + return false, errors.New("瑙g爜澶辫触") + } + if deleteRes == -1 { + result = false + } else { + result = true + } + return result, nil +} + +//缁欐墍鏈夎妭鐐硅拷鍔犲垹闄や换鍔′俊鎭� +func AddDelTask(serverIp string, serverPort string, indexName string, startTime string, endTime string, analyServerId string) (result bool, err error) { + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query" + addJson := `{ + "script": { + "lang":"painless", + "inline": "ctx._source.instantTask.add(params.newtask)", + "params": { + "newtask": { + "instantClearId": "` + analyServerId + `", + "startTime": "` + startTime + `", + "endTime": "` + endTime + `" + } + } + }, + "query": { + "bool": { + "filter": [ + { + "term": { + "application": "loopCoverage" + } + } + ] + } + } +}` + buf, err := EsReq("POST", url, []byte(addJson)) + if err != nil { + return false, errors.New("璇锋眰澶辫触") + } + updateRes, err := SourceUpdated(buf) + if err != nil { + return false, errors.New("瑙g爜澶辫触") + } + if updateRes == -1 { + result = false + } else { + result = true + } + return result, nil +} + +//绉婚櫎宸叉墽琛屽畬鐨勫垹闄や换鍔� +func DeleteDelTask(serverIp string, serverPort string, indexName string, analyServerId string) (result bool, err error) { + url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query" + deleteJson := `{ + "script": { + "lang":"painless", + "inline": "ctx._source.instantTask.remove(0)" + }, + "query": { + "bool": { + "filter":[{ + "term":{ + "id":"` + analyServerId + `" + } + }] + } + } +}` + buf, err := EsReq("POST", url, []byte(deleteJson)) + if err != nil { + return false, errors.New("璇锋眰澶辫触") + } + updateRes, err := SourceUpdated(buf) + if err != nil { + return false, errors.New("瑙g爜澶辫触") + } + if updateRes == -1 { + result = false + } else { + result = true + } + return result, nil +} + +type ShardInfo struct { + ShardIndex string `json:"shardIndex"` //鍒嗙墖鎵�灞炵储寮曞悕绉� + ShardNum int `json:"shardNum"` //鍒嗙墖鍙� + ShardRole string `json:"shardRole"` //鍒嗙墖瑙掕壊(涓诲垎鐗囷細primary 鍓湰鍒嗙墖锛歳eplica) + ShardState string `json:"shardState"` //鍒嗙墖鐘舵��(鍚敤锛歋TARTED 鏈惎鐢細UNASSIGNED) + ShardDocs int `json:"shardDocs"` //鍒嗙墖宸蹭繚瀛樻枃妗f暟 + ShardStore string `json:"shardStore"` //鍒嗙墖褰撳墠瀛樺偍鏁版嵁澶у皬 + ShardIp string `json:"shardIp"` //鍒嗙墖鎵�鍦ㄨ妭鐐筰p + ShardNode string `json:"shardNode"` //鍒嗙墖鎵�鍦ㄨ妭鐐瑰悕绉� +} + +//鑾峰彇绱㈠紩鍒嗙墖淇℃伅 +func GetShardsByIndex(serverIp string, serverPort string, indexName string) ([]ShardInfo, error) { + url := "http://" + serverIp + ":" + serverPort + "/_cat/shards?v" + buf, err := EsReq("GET", url, []byte("")) + if err != nil { + return nil, err + } + var inf = []ShardInfo{} + res := strings.Split(string(buf), "\n")[1:] + for _, r := range res { + if r != "" { + + inx := strings.Fields(r) + index := inx[0] + shard, _ := strconv.Atoi(inx[1]) + prired := inx[2] + if prired == "r" { + prired = "replica" + } + if prired == "p" { + prired = "primary" + } + state := inx[3] + docs := 0 + store := "" + ip := "" + node := "" + if state == "STARTED" { + docs, _ = strconv.Atoi(inx[4]) + store = inx[5] + ip = inx[6] + node = inx[7] + } + if index == indexName { + inf = append(inf, ShardInfo{ + ShardIndex: index, + ShardNum: shard, + ShardRole: prired, + ShardState: state, + ShardDocs: docs, + ShardStore: store, + ShardIp: ip, + ShardNode: node, + }) + + } + } + + } + return inf, nil } -- Gitblit v1.8.0