sunty
2024-03-27 1278c1f6b6e79238b520513c80ce26882e805f71
EsApi.go
@@ -1,15 +1,15 @@
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{}) {
@@ -22,6 +22,404 @@
   }
}
//***********************重庆Start**********************************//
type activeHourFormat struct {
   startTime string
   endTime   string
   startHour int
   endHour   int
}
//按需求(activeHourFormat结构体)格式化时间数据
func formatActiveHour(activeHour string) (activeHourFormat, error) {
   hours := strings.Split(activeHour, "-")
   if len(hours) == 2 {
      startHour := hours[0]
      endHour := hours[1]
      // 解析开始时间的小时和分钟
      startParts := strings.Split(startHour, ":")
      startHourInt, _ := strconv.Atoi(startParts[0])
      // 解析结束时间的小时和分钟
      endParts := strings.Split(endHour, ":")
      endHourInt, _ := strconv.Atoi(endParts[0])
      // 输出开始时间的小时
      fmt.Println("开始时间的小时:", startHourInt)
      // 输出结束时间的小时 + 1
      endHourPlusOne := (endHourInt + 1) % 24 // 取余确保不超过24小时
      fmt.Println("结束时间的小时 + 1:", endHourPlusOne)
      activeHourFormat := activeHourFormat{startTime: startHour, endTime: endHour, startHour: startHourInt, endHour: endHourPlusOne}
      return activeHourFormat, nil
   }
   return activeHourFormat{}, errors.New("错误:无法解析开始时间和结束时间")
}
//判断时间是否再范围之内
func isTimeInRange(timeStr, startStr, endStr string) bool {
   layout := "15:04:05"
   timeStamp, err := time.Parse(layout, timeStr)
   if err != nil {
      fmt.Println("Error parsing timestamp:", err)
      return false
   }
   startTime, err := time.Parse(layout, startStr)
   if err != nil {
      fmt.Println("Error parsing start time:", err)
      return false
   }
   endTime, err := time.Parse(layout, endStr)
   if err != nil {
      fmt.Println("Error parsing end time:", err)
      return false
   }
   if startTime.After(endTime) {
      // 跨越日期的情况
      return timeStamp.After(startTime) || timeStamp.Before(endTime)
   } else {
      // 不跨越日期的情况
      return timeStamp.After(startTime) && timeStamp.Before(endTime)
   }
}
//判断两个时间先后
func compareTimes(time1Str, time2Str string) int {
   layout := "15:04:05"
   time1, err := time.Parse(layout, time1Str)
   if err != nil {
      fmt.Println("Error parsing time 1:", err)
      return 0
   }
   time2, err := time.Parse(layout, time2Str)
   if err != nil {
      fmt.Println("Error parsing time 2:", err)
      return 0
   }
   if time1.Before(time2) {
      return -1 // time1 在 time2 之前
   } else if time1.After(time2) {
      return 1 // time1 在 time2 之后
   } else {
      return 0 // time1 和 time2 相等
   }
}
//判断日期相差几天
func daysBetweenDates(date1Str, date2Str string) int {
   layout := "2006-01-02"
   date1, err := time.Parse(layout, date1Str)
   if err != nil {
      fmt.Println("Error parsing date 1:", err)
      return 0
   }
   date2, err := time.Parse(layout, date2Str)
   if err != nil {
      fmt.Println("Error parsing date 2:", err)
      return 0
   }
   duration := date2.Sub(date1)
   days := int(duration.Hours() / 24)
   return days
}
//计算时间阈值
func checkTimeDifference(timestampStr1 string, timestampStr2 string, intervalInMinutes int) bool {
   layout := "2006-01-02 15:04:05"
   timestampStr1 = timestampStr1[:19]
   timestampStr2 = timestampStr2[:19]
   // 将字符串解析为时间
   time1, err := time.Parse(layout, timestampStr1)
   if err != nil {
      fmt.Println("时间解析失败:", err)
      return false
   }
   time2, err := time.Parse(layout, timestampStr2)
   if err != nil {
      fmt.Println("时间解析失败:", err)
      return false
   }
   // 计算时间差
   diff := time2.Sub(time1)
   // 检查时间差是否小于等于指定的间隔
   if diff.Minutes() <= float64(intervalInMinutes) {
      return true
   } else {
      return false
   }
}
////格式化时间hh:mm:ss:zzz to hh:mm:ss
//func formatTime(inputTime string) (string, error) {
//   parsedTime, err := time.Parse("15:04:05:000", inputTime)
//   if err != nil {
//      return "", err
//   }
//
//   formattedTime := parsedTime.Format("15:04:05")
//   return formattedTime, nil
//}
func resetDataId(dataId []string, id, dDate, dTime string, sDate *string, sTime *string) []string {
   dataId = make([]string, 0)
   *sDate = dDate
   *sTime = dTime
   dataId = append(dataId, id)
   return dataId
}
func decodeActivityId(aHFormat activeHourFormat, frequency int, intervalInMinutes int, source []map[string]interface{}) ([]map[string]interface{}, error) {
   docInfo := make([]map[string]interface{}, 0)
   for _, info := range source {
      tmpInfo := make(map[string]interface{})
      activeId := make([]string, 0)
      sDate := ""
      sTime := ""
      documentNumber := info["key"].(string)
      tmpInfo["documentNumber"] = documentNumber
      //fmt.Println("documentNumber: ", documentNumber)
      topHits := info["top_hits"].(map[string]interface{})
      hits := topHits["hits"].(map[string]interface{})
      hitsResult := hits["hits"].([]interface{})
      dataId := make([]string, 0)
      for sIndex, sourceInfo := range hitsResult {
         rSourceInfo := sourceInfo.(map[string]interface{})
         source := rSourceInfo["_source"].(map[string]interface{})
         captureTime := source["picDate"].(string)
         dDate := strings.Split(captureTime, " ")[0]
         dTime := strings.Split(captureTime[:19], " ")[1]
         //fmt.Println(captureTime, dDate, dTime)
         id := source["id"].(string)
         //fmt.Println("sindex: ", sIndex, "documentNumber", tmpInfo["documentNumber"], "id: ", id, "captureTime: ", captureTime)
         if !isTimeInRange(dTime, aHFormat.startTime, aHFormat.endTime) {
            if sDate != "" && len(dataId) >= frequency {
               activeId = append(activeId, dataId...)
               dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
            }
            continue
         }
         if sDate == "" {
            sDate = dDate
            sTime = dTime
            dataId = append(dataId, id)
            if len(dataId) >= frequency {
               activeId = append(activeId, dataId...)
               dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
            }
            continue
         }
         if checkTimeDifference(sDate+" "+sTime, captureTime[:19], intervalInMinutes) {
            if len(dataId) >= frequency {
               activeId = append(activeId, dataId...)
               dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
            }
            continue
         }
         //fmt.Println(daysBetweenDates(sDate, dDate))
         if aHFormat.startHour < aHFormat.endHour && daysBetweenDates(sDate, dDate) == 0 {
            dataId = append(dataId, id)
         } else if aHFormat.startHour > aHFormat.endHour {
            if daysBetweenDates(sDate, dDate) == 0 {
               if compareTimes(dTime, aHFormat.startTime) == compareTimes(sTime, aHFormat.startTime) {
                  //   ||compareTimes(dTime,aHFormat.endTime) == compareTimes(sTime, aHFormat.endTime){
                  dataId = append(dataId, id)
               }
            } else if daysBetweenDates(sDate, dDate) == 1 {
               //初始时间戳在结束范围之前
               if compareTimes(sTime, aHFormat.endTime) == -1 {
                  if len(dataId) >= frequency {
                     activeId = append(activeId, dataId...)
                     dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
                  }
                  //初始时间戳在开始范围之后
               } else if compareTimes(sTime, aHFormat.endTime) == 1 {
                  //next时间戳在结束范围之前
                  if compareTimes(dTime, aHFormat.endTime) == -1 {
                     dataId = append(dataId, id)
                     //next时间戳在开始范围之后
                  } else if compareTimes(dTime, aHFormat.startTime) == 1 {
                     if len(dataId) >= frequency {
                        activeId = append(activeId, dataId...)
                        dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
                     }
                  }
               }
            } else if daysBetweenDates(sDate, dDate) >= 1 {
               //fmt.Println(len(dataId))
               if len(dataId) >= frequency {
                  activeId = append(activeId, dataId...)
                  dataId = resetDataId(dataId, id, dDate, dTime, &sDate, &sTime)
               }
            }
         }
         if sIndex == len(hitsResult)-1 {
            if len(dataId) >= frequency {
               activeId = append(activeId, dataId...)
            }
         }
      }
      if len(activeId) > 0 {
         tmpInfo["id"] = activeId
         docInfo = append(docInfo, tmpInfo)
      }
   }
   return docInfo, nil
}
func DayNightActivityQuery(communityId string, documentNumber string,startTime string, endTime string, activeHour string, frequency int,
   intervalInMinutes int, indexName string, serverIp string, serverPort string) (map[string]interface{}, error) {
   esURL := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search"
   aHFormat, err := formatActiveHour(activeHour)
   if err != nil {
      return nil, err
   }
   filterDocIdAttr := ""
   if documentNumber != ""{
      filterDocIdAttr = "{\"term\": {\""+documentNumber+"\": \"\"}},"
   }
   queryDSL := `
   {
       "size": 0,
       "query": {
           "bool": {
               "filter": [
                   {
                       "range": {
                           "picDate": {
                               "gte": "` + startTime + `",
                               "lt": "` + endTime + `"
                           }
                       }
                   },
               `+filterDocIdAttr+`
                   {
                       "term": {
                           "communityId": "` + communityId + `"
                       }
                   },
                   {
                       "script": {
                           "script": {
                               "source": "doc['picDate'].value.hourOfDay >= ` + strconv.Itoa(aHFormat.startHour) + ` || doc['picDate'].value.hourOfDay < ` + strconv.Itoa(aHFormat.endHour) + `",
                               "lang": "painless"
                           }
                       }
                   }
               ],
               "must_not": [
                   {
                       "term": {
                           "documentNumber": ""
                       }
                   }
               ]
           }
       },
       "aggs": {
           "group_by_documentnumber": {
               "terms": {
                   "field": "documentNumber",
                   "size": 100000
               },
            "aggs": {
               "top_hits": {
                      "top_hits": {
                          "_source": [
                        "id",
                              "picDate"
                     ],
                           "size": 100000,
                           "sort": [
                               {
                                   "picDate": {
                                       "order": "asc"
                                   }
                               }
                           ]
                  }
               }
               }
           }
       }
   }`
   //fmt.Println(esURL)
   //fmt.Println(queryDSL)
   var result = make(map[string]interface{})
   buf, err := EsReq("POST", esURL, []byte(queryDSL))
   if err != nil {
      return nil, err
   }
   source, err := SourceAggregationList(buf)
   if err != nil {
      return nil, err
   }
   //fmt.Println(source)
   docResult, err := decodeActivityId(aHFormat, frequency, intervalInMinutes, source)
   if err != nil {
      return nil, err
   }
   //result, _ := decodeDocumentInfos(source)
   //return result, nil
   if len(docResult) ==0 {
      return result,nil
   }
   DataInfos, err := GetInfosByIds(docResult[0]["id"].([]string), indexName, serverIp, serverPort)
   result["documentNumbers"] = docResult
   result["datalist"] = DataInfos
   return result, nil
}
func GetInfosByIds(ids []string, indexName string, serverIp string, serverPort string) ([]map[string]interface{}, error) {
   captureIds := strings.Replace(strings.Trim(fmt.Sprint(ids), "[]"), " ", "\",\"", -1)
   esURL := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search"
   queryDSL := `
            {
               "query": {
                  "bool": {
                     "filter": [{
                        "terms": {
                           "id": [
                              "` + captureIds + `"
                           ]
                        }
                     }]
                  }
               },
                "size":1000000,
            "sort":[{"picDate":{"order":"desc"}}],
            "_source": {"includes":[],"excludes":["*.feature"]}
            }
`
   buf, err := EsReq("POST", esURL, []byte(queryDSL))
   if err != nil {
      return nil, err
   }
   sources, err := Sourcelist(buf)
   if err != nil {
      return nil, err
   }
   return sources, nil
}
// ***********************重庆End************************************//
// 根据抓拍人员id查询抓拍人员信息
func AIOceaninfosbyid(id []string, indexName string, serverIp string, serverPort string) ([]protomsg.AIOcean, error) {
   var aIOceanInfo []protomsg.AIOcean
@@ -56,7 +454,43 @@
   return aIOcean, nil
}
//根据抓拍库人员id查询特征值
// 根据抓拍人员id查询视频地址
func AIOceanVideoUrlbyid(id string, indexName string, serverIp string, serverPort string) (string, error) {
   //var aIOceanInfo []protomsg.AIOcean
   //videopersonsPersonId := strings.Replace(strings.Trim(fmt.Sprint(id), "[]"), " ", "\",\"", -1)
   var dbinfoRequest = `
      {
          "query": {
              "bool": {
                  "filter": [
                      {
                          "term": {
                                "id": "` + id + `"
                          }
                      }
                  ]
              }
          },
          "_source": [
              "videoUrl"
          ]
      }
        `
   buf, err := EsReq("POST", "http://"+serverIp+":"+serverPort+"/"+indexName+"/_search", []byte(dbinfoRequest))
   if err != nil {
      return "", err
   }
   sources, err := Sourcelist(buf)
   if err != nil {
      return "", err
   }
   videoUrl := sources[0]["videoUrl"].(string)
   //aIOcean := AIOceanAnalysis(sources)
   return videoUrl, nil
}
// 根据抓拍库人员id查询特征值
func GetVideoPersonFaceFeatureById(id string, indexName string, serverIp string, serverPort string) (string, error) {
   var jsonDSL = `
            {
@@ -86,7 +520,7 @@
   return feature, nil
}
//根据目标id查询已追加条数
// 根据目标id查询已追加条数
func GetLinkTagInfoSize(id string, indexName string, serverIp string, serverPort string) (size int, err error) {
   url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search"
   queryDSL := `{
@@ -112,7 +546,7 @@
   return size, nil
}
//根据目标id追加跟踪信息
// 根据目标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")
@@ -159,11 +593,224 @@
}
//根据时间范围,摄像机列表,分组聚合人脸列表
func GetfaceDataBucketsBycameraIdAndTime(cameraId []string, startTime string, endTime string, thresholdTime float64, serverIp string, ServerPort string, indexName string) (buckersDate map[string]interface{}, err error) {
   esCameraId := strings.Replace(strings.Trim(fmt.Sprint(cameraId), "[]"), " ", "\",\"", -1)
   var buckersUrl = "http://" + serverIp + ":" + ServerPort + "/" + indexName + "/_search"
   var buckersBody = `{
/**************************************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": [
@@ -179,12 +826,235 @@
                    "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 + `"
                        }
                    }
                },
                {
                    "terms": {
                        "cameraId": ["` + esCameraId + `"]
                    "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 + `
            ]
        }
    },
@@ -207,12 +1077,13 @@
                            }
                        }
                    }
                ]
                ],
                "size": 10000000
            },
            "aggs":{
                "top_attention_hits":{
                    "top_hits":{
                        "size": 100,
                        "size": 1000000,
                        "sort": [
                            {
                                "picDate": {
@@ -221,7 +1092,7 @@
                            }
                        ],
                        "_source":{
                            "includes":["baseInfo.targetId","cameraId","cameraName","cameraAddr","targetInfo.targetScore","targetInfo.picSmUrl","showLabels","baseInfo.tableId","baseInfo.tableName","baseInfo.bwType","baseInfo.targetName","baseInfo.compareScore","picDate","picMaxUrl"]
                            "includes":["baseInfo.targetId","cameraId","cameraName","cameraAddr","targetInfo.targetScore","targetInfo.picSmUrl","showLabels","baseInfo.tableId","baseInfo.tableName","baseInfo.bwType","baseInfo.targetName","baseInfo.compareScore","picDate","picMaxUrl","picWH"]
                        }
                    }
                }
@@ -229,33 +1100,141 @@
        }
    }
}`
   //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
   }
   sources, err := SourceAggregations(buf, thresholdTime)
   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
}
//根据抓拍人员id更新(picurl)图片地址---预开发
func UpdatePicUrlById(id string, picUrl string, indexName string, serverIp string, serverPort string) (err error) {
// 根据时间范围,摄像机列表,分组聚合人脸列表
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更新(picurl)图片地址
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 := `
        "lang":"painless",
        "inline": "ctx._source.picMaxUrl.add(` + picUrl + `)"
   sourceStr := `
        "source": "ctx._source.picMaxUrl.add('` + picUrl + `');ctx._source.updateTime='` + updateTime + `'"
`
   if len(picMaxUrls) >= 2 {
      sourceStr = `"source": "ctx._source.picMaxUrl[1]='` + picUrl + `'"`
      sourceStr = `"source": "ctx._source.picMaxUrl[1]='` + picUrl + `';ctx._source.updateTime='` + updateTime + `'"`
   }
   var info interface{}
   url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_update_by_query?refresh=true"
@@ -294,7 +1273,7 @@
   }
   middle, ok := out["updated"].(float64)
   if !ok {
      logPrint("first updated change error!")
      logPrint("first updated change error!", out)
      return errors.New("first updated change error!")
   }
   if middle == 1 {
@@ -306,7 +1285,7 @@
   return nil
}
//根据抓拍人员id更新(videourl)摄像机地址
// 根据抓拍人员id更新(videourl)摄像机地址
func UpdateVideourlById(id string, videoUrl string, indexName string, serverIp string, serverPort string, command int) (statu int, err error) {
   var info interface{}
@@ -343,23 +1322,30 @@
      return statu, errors.New("http response interface can not change map[string]interface{}")
   }
   middle, ok := out["updated"].(float64)
   if !ok {
   batches, ok1 := out["batches"].(float64)
   if !ok || !ok1 {
      logPrint("first updated change error!")
      statu = 500
      return statu, errors.New("first updated change error!")
   }
   if middle == 1 {
      statu = 200
      return statu, nil
   }
   if middle == 0 {
      statu = 201
      return statu, errors.New("已经修改")
   if batches == 0 {
      logPrint("no such doc in database")
      statu = 400
      return statu, errors.New("目标数据不存在")
   } else {
      if middle == 1 {
         statu = 200
         return statu, nil
      }
      if middle == 0 {
         statu = 201
         return statu, errors.New("已经修改")
      }
   }
   return statu, nil
}
//获取当前节点抓拍库所有人员ID*缓存*
// 获取当前节点抓拍库所有人员ID*缓存*
func GetAllLocalVideopersonsId(compareArgs protomsg.CompareArgs, indexName string, serverIp string, serverPort string, alarmLevelTypes string) (capturetable []string) {
   queryStr := ""
   queryBody := compareArgs.InputValue
@@ -399,7 +1385,12 @@
   isCollectStr := ""
   isCollect := compareArgs.Collection
   if isCollect != "" {
      isCollectStr = "{\"term\":{\"isCollect\":\"" + isCollect + "\"}},"
      //isCollectStr = "{\"term\":{\"isCollect\":\"" + isCollect + "\"}},"
      if isCollect == "1" {
         isCollectStr = "{\"term\":{\"isCollect\":true}},"
      } else if isCollect == "0" {
         isCollectStr = "{\"term\":{\"isCollect\":false}},"
      }
   }
   //判断布防等级
@@ -523,7 +1514,7 @@
   return capturetable
}
//初始化实时抓拍
// 初始化实时抓拍
func InitRealTimeCapture(serverIp string, serverPort string, indexName string, isAlarm string, category string, quantity int) ([]protomsg.AIOcean, error) {
   var aIOceanInfo []protomsg.AIOcean
   url := "http://" + serverIp + ":" + serverPort +
@@ -540,7 +1531,7 @@
   if category != "all" {
      filterArr = append(filterArr, `            {
               "term":{
                  "targetInfo.targetType":"`+category+`"
                  "targetInfo.targetType.raw":"`+category+`"
               }
            }`)
@@ -560,7 +1551,7 @@
   "sort":[{"picDate":{"order":"desc"}}],
   "_source": {"includes":[],"excludes":["*.feature"]}
   }`
   logPrint(DSLJson)
   //logPrint(DSLJson)
   buf, err := EsReq("POST", url, []byte(DSLJson))
   if err != nil {
      return aIOceanInfo, err
@@ -576,7 +1567,7 @@
   return aIOcean, nil
}
//实时抓拍
// 实时抓拍
func RealTimeCapture(serverIp string, serverPort string, indexName string, isAlarm bool) ([]protomsg.AIOcean, error) {
   var aIOceanInfo []protomsg.AIOcean
   url := "http://" + serverIp + ":" + serverPort +
@@ -620,7 +1611,7 @@
   return aIOcean, nil
}
//综合统计
// 综合统计
func StatisticsComprehensive(serverIp string, serverPort string, indexName string, isAlarm string) (total int, err error) {
   url := "http://" + serverIp + ":" + serverPort +
      "/" + indexName + "/_search"
@@ -650,7 +1641,6 @@
         }
      }
   }`
   //logPrint(DSLJson)
   buf, err := EsReq("POST", url, []byte(DSLJson))
   if err != nil {
      return total, err
@@ -670,7 +1660,7 @@
   return total, nil
}
//实时报警任务比率
// 实时报警任务比率
func RealTimeAlarmTaskRate(serverIp string, serverPort string, indexName string) (sources []map[string]interface{}, err error) {
   url := "http://" + serverIp + ":" + serverPort +
      "/" + indexName + "/_search"
@@ -688,9 +1678,9 @@
      }
   },
   "aggs":{
      "sdkName_status":{
      "taskName_status":{
         "terms":{
            "field":"sdkName.raw"
            "field":"taskName.raw"
         }
      }
   }
@@ -709,11 +1699,11 @@
   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{})
@@ -731,11 +1721,20 @@
   return sources, nil
}
//聚合任务列表,taskId+taskName
func AggregateTaskList(serverIp string, serverPort string, indexName string, analyServerId string) (sources []map[string]interface{}, err error) {
// 聚合任务列表,taskId+taskName
func AggregateTaskList(serverIp string, serverPort string, indexName string, analyServerId string, cameraIds []string) (sources []map[string]interface{}, err error) {
   url := "http://" + serverIp + ":" + serverPort +
      "/" + indexName + "/_search"
   serverFilterStr := ""
   cameIdFilterStr := ""
   if cameraIds != nil && len(cameraIds) > 0 {
      cameIdsStr := strings.Replace(strings.Trim(fmt.Sprint(cameraIds), "[]"), " ", "\",\"", -1)
      cameIdFilterStr = `,{
            "term": {
            "cameraId": "` + cameIdsStr + `"
               }
                }`
   }
   if analyServerId != "" {
      serverFilterStr = `,
         "query": {
@@ -744,8 +1743,9 @@
            {
            "term": {
            "analyServerId": "` + analyServerId + `"
               }
            }
            }
             ` + cameIdFilterStr + `
         ]
         }
      }`
@@ -817,7 +1817,7 @@
}
//添加即将删除信号
// 添加即将删除信号
func AddDeleteSignal() {
}
@@ -858,7 +1858,7 @@
}
//查询时间段数据 *缓存*
// 查询时间段数据 *缓存*
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"
@@ -1031,13 +2031,13 @@
   }
   wg.Wait()
   fmt.Println("lenth_all: ", len(dbinfos))
   //fmt.Println("lenth_all: ", len(dbinfos))
   return dbinfos, nil
}
//************************CORN TASK*******************************
//查询日期范围内是否还存在数据
// ************************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 := `{
@@ -1076,8 +2076,8 @@
   return result, nil
}
//按日期范围,服务器Id删除数据
func DeleteAnalyServerData(serverIp string, serverPort string, indexName string, startTime string, endTime string, analyServerId string) (result bool, err error) {
// 按日期范围,服务器Id删除数据
func DeleteAnalyServerData(serverIp string, serverPort string, indexName string, startTime string, endTime string, analyServerId string) (total int, err error) {
   url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_delete_by_query"
   deleteJson := `{
   "query":{
@@ -1099,23 +2099,20 @@
      }
   }
}   `
   fmt.Println(url)
   fmt.Println(deleteJson)
   buf, err := EsReq("POST", url, []byte(deleteJson))
   if err != nil {
      return false, errors.New("请求失败")
      return -1, errors.New("请求失败")
   }
   deleteRes, err := SourceDeleted(buf)
   if err != nil {
      return false, errors.New("解码失败")
      return -1, errors.New("解码失败")
   }
   if deleteRes == -1 {
      result = false
   } else {
      result = true
   }
   return result, nil
   return deleteRes, 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 := `{
@@ -1158,7 +2155,7 @@
   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 := `{
@@ -1191,3 +2188,66 @@
   }
   return result, nil
}
type ShardInfo struct {
   ShardIndex string `json:"shardIndex"` //分片所属索引名称
   ShardNum   int    `json:"shardNum"`   //分片号
   ShardRole  string `json:"shardRole"`  //分片角色(主分片:primary 副本分片:replica)
   ShardState string `json:"shardState"` //分片状态(启用:STARTED 未启用:UNASSIGNED)
   ShardDocs  int    `json:"shardDocs"`  //分片已保存文档数
   ShardStore string `json:"shardStore"` //分片当前存储数据大小
   ShardIp    string `json:"shardIp"`    //分片所在节点ip
   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
}