sunty
2024-03-27 14744fad5fd0c49935a9cec5c7a49102758f996a
EsApi.go
@@ -31,6 +31,7 @@
   endHour   int
}
//按需求(activeHourFormat结构体)格式化时间数据
func formatActiveHour(activeHour string) (activeHourFormat, error) {
   hours := strings.Split(activeHour, "-")
@@ -47,11 +48,11 @@
      endHourInt, _ := strconv.Atoi(endParts[0])
      // 输出开始时间的小时
      fmt.Println("开始时间的小时:", startHourInt)
      //fmt.Println("开始时间的小时:", startHourInt)
      // 输出结束时间的小时 + 1
      endHourPlusOne := (endHourInt + 1) % 24 // 取余确保不超过24小时
      fmt.Println("结束时间的小时 + 1:", endHourPlusOne)
      //fmt.Println("结束时间的小时 + 1:", endHourPlusOne)
      activeHourFormat := activeHourFormat{startTime: startHour, endTime: endHour, startHour: startHourInt, endHour: endHourPlusOne}
      return activeHourFormat, nil
   }
@@ -59,15 +60,245 @@
}
func DayNightActivityQuery(communityId string, startTime string, endTime string, activeHour string, indexName string, serverIp string, serverPort string) ([]string, error) {
   activityId := make([]string, 0)
//判断时间是否再范围之内
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(comIds []string, docNumber 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"
   activeHourFormat, err := formatActiveHour(activeHour)
   aHFormat, err := formatActiveHour(activeHour)
   if err != nil {
      return nil, err
   }
   filterDocIdAttr := ""
   if docNumber != "" {
      filterDocIdAttr = "{\"term\": {\"documentNumber\": \"" + docNumber + "\"}},"
   }
   comIdsStr := ""
   if comIds == nil || len(comIds) > 0 {
      esComIds := strings.Replace(strings.Trim(fmt.Sprint(comIds), "[]"), " ", "\",\"", -1)
      comIdsStr = "{\"terms\":{\"communityId\":[\"" + esComIds + "\"]}},"
   }
   queryDSL := `
   {
       "size": 0,
@@ -82,15 +313,12 @@
                           }
                       }
                   },
                   {
                       "term": {
                           "communityId": "` + communityId + `"
                       }
                   },
               ` + filterDocIdAttr + `
                ` + comIdsStr + `
                   {
                       "script": {
                           "script": {
                               "source": "doc['picDate'].value.hourOfDay >= ` + strconv.Itoa(activeHourFormat.startHour) + ` || doc['picDate'].value.hourOfDay < ` + strconv.Itoa(activeHourFormat.endHour) + `",
                               "source": "doc['picDate'].value.hourOfDay >= ` + strconv.Itoa(aHFormat.startHour) + ` || doc['picDate'].value.hourOfDay < ` + strconv.Itoa(aHFormat.endHour) + `",
                               "lang": "painless"
                           }
                       }
@@ -111,24 +339,342 @@
                   "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
}
type acmInfo struct {
   documentNumber string
   camerasInfos   []camerasInfo
}
type camerasInfo struct {
   cameraId     string
   captureInfos []captureInfo
}
type captureInfo struct {
   id      string
   picDate string
}
func addSecondsToTimestamp(timestamp string, seconds int) (string, error) {
   parsedTime, err := time.Parse("2006-01-02 15:04:05", timestamp)
   if err != nil {
      return "", err
   }
   newTime := parsedTime.Add(time.Second * time.Duration(seconds))
   newTimestamp := newTime.Format("2006-01-02 15:04:05")
   return newTimestamp, nil
}
func decodeInfo(intervalInMinutes int, source []map[string]interface{}) ([]acmInfo, error) {
   acmInfos := make([]acmInfo, 0)
   for _, info := range source {
      var aInfo acmInfo
      documentNumber := info["key"].(string)
      aInfo.documentNumber = documentNumber
      groupByCameraId := info["group_by_cameraId"].(map[string]interface{})
      cameraBuckets := groupByCameraId["buckets"].([]interface{})
      for _, cameraInfo := range cameraBuckets {
         var camsInfo camerasInfo
         cInfo := cameraInfo.(map[string]interface{})
         cameraId := cInfo["key"].(string)
         camsInfo.cameraId = cameraId
         dataBuckets := cInfo["top_hits"].(map[string]interface{})["hits"].(map[string]interface{})["hits"].([]interface{})
         markTime := ""
         for _, dataInfo := range dataBuckets {
            var capInfo captureInfo
            dInfo := dataInfo.(map[string]interface{})
            dSource := dInfo["_source"].(map[string]interface{})
            id := dSource["id"].(string)
            picDate := dSource["picDate"].(string)
            //addFlag := false
            if markTime == "" {
               //addFlag = true
               markTime = picDate
            } else {
               if checkTimeDifference(markTime, picDate, intervalInMinutes) {
                  //fmt.Println(markTime, picDate)
                  markTime = picDate
                  continue
               }
               markTime = picDate
            }
            capInfo.id = id
            capInfo.picDate = picDate
            camsInfo.captureInfos = append(camsInfo.captureInfos, capInfo)
         }
         aInfo.camerasInfos = append(aInfo.camerasInfos, camsInfo)
      }
      acmInfos = append(acmInfos, aInfo)
   }
   return acmInfos, nil
}
type addResultIds struct {
   documentNumber string
   unionIds       []unionId
}
type unionId struct {
   baseId   string
   targetId string
}
func addResultInfo(source []map[string]interface{}, targetAddResultIds *[]addResultIds, bId string) {
   found := false
   for _, info := range source {
      documentNumber := info["key"].(string)
      dataBuckets := info["top_hits"].(map[string]interface{})["hits"].(map[string]interface{})["hits"].([]interface{})
      id := dataBuckets[0].(map[string]interface{})["_source"].(map[string]interface{})["id"].(string)
      //fmt.Println("documentNumber: ", documentNumber, "\tid: ", id)
      for i, docInfo := range *targetAddResultIds {
         if documentNumber == docInfo.documentNumber {
            //fmt.Println("新更新")
            (*targetAddResultIds)[i].unionIds = append((*targetAddResultIds)[i].unionIds, unionId{baseId: bId, targetId: id})
            found = true
            break
         }
      }
      if !found {
         //fmt.Println("新添加")
         var targetAddResultId addResultIds
         targetAddResultId.documentNumber = documentNumber
         targetAddResultId.unionIds = append(targetAddResultId.unionIds, unionId{baseId: bId, targetId: id})
         *targetAddResultIds = append(*targetAddResultIds, targetAddResultId)
      }
   }
}
func removeDuplicates(nums []string) []string {
   result := make([]string, 0)
   seen := make(map[string]bool)
   for _, num := range nums {
      if !seen[num] {
         result = append(result, num)
         seen[num] = true
      }
   }
   return result
}
func findAnalyzeCoordinatedMovementsInfos(infos []acmInfo, beforeTime int, afterTime int, frequency int,
   indexName string, serverIp string, serverPort string) (map[string]interface{}, error) {
   //baseAddResultIds := make([]addResultIds, 0)
   targetAddResultIds := make([]addResultIds, 0)
   esURL := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search"
   for _, info := range infos {
      for _, cInfo := range info.camerasInfos {
         for _, pInfo := range cInfo.captureInfos {
            gteDate, err := addSecondsToTimestamp(pInfo.picDate[:19], beforeTime)
            if err != nil {
               fmt.Println(err)
            }
            lteDate, err := addSecondsToTimestamp(pInfo.picDate[:19], afterTime)
            if err != nil {
               fmt.Println(err)
            }
            queryDSL := `
               {
                   "size": 0,
                   "query": {
                       "bool": {
                           "filter": [
                               {
                                   "range": {
                                       "picDate": {
                                           "gte": "` + gteDate + `",
                                           "lte": "` + lteDate + `"
                                       }
                                   }
                               },
                               {
                                   "term": {
                                       "cameraId": "` + cInfo.cameraId + `"
                                   }
                               }
                           ]
                       }
                   },
                   "aggs": {
                       "group_by_documentnumber": {
                           "terms": {
                               "field": "documentNumber",
                               "size": 100000
                           },
                           "aggs": {
                               "top_hits": {
                                   "top_hits": {
                                       "_source": [
                                           "id",
                                           "cameraId",
                                           "picDate"
                                       ],
                                       "size": 10000,
                                       "sort": [
                                           {
                                               "picDate": {
                                                   "order": "asc"
                                               }
                                           }
                                       ]
                                   }
                               }
                           }
                       }
                   }
               }`
            //fmt.Println(esURL, queryDSL)
            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("pInfo.id: ", pInfo.id)
            addResultInfo(source, &targetAddResultIds, pInfo.id)
            //fmt.Println("targetAddResultIds: ", targetAddResultIds)
            if err != nil {
               return nil, err
            }
            //fmt.Println(source)
         }
      }
   }
   //fmt.Println("targetAddResultIds: ", targetAddResultIds)
   baseIds := make([]string, 0)
   targetIds := make([]string, 0)
   for _, tAIdInfo := range targetAddResultIds {
      if len(tAIdInfo.unionIds) >= frequency {
         for _, unionId := range tAIdInfo.unionIds {
            baseIds = append(baseIds, unionId.baseId)
            targetIds = append(targetIds, unionId.targetId)
         }
      }
   }
   rdbaseIds := removeDuplicates(baseIds)
   rdtargetIds := removeDuplicates(targetIds)
   baseInfos, err := GetInfosByIds(rdbaseIds, indexName, serverIp, serverPort)
   if err != nil{
      return nil, err
   }
   targetInfos, err := GetInfosByIds(rdtargetIds, indexName, serverIp, serverPort)
   if err != nil{
      return nil, err
   }
   result := make(map[string]interface{})
   result["baseRecordInfo"] = baseInfos
   result["targetRecordInfo"] = targetInfos
   return result, nil
}
func AnalyzeCoordinatedMovements(comIds []string, docNumber string, startDate string, endDate string, beforeTime int, afterTime int, frequency int,
   intervalInMinutes int, indexName string, serverIp string, serverPort string) (map[string]interface{}, error) {
   esURL := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_search"
   //判断社区IDs
   comIdsStr := ""
   if comIds == nil || len(comIds) > 0 {
      esComIds := strings.Replace(strings.Trim(fmt.Sprint(comIds), "[]"), " ", "\",\"", -1)
      comIdsStr = "{\"terms\":{\"communityId\":[\"" + esComIds + "\"]}},"
   }
   queryDSL := `
   {
       "size": 0,
       "query": {
           "bool": {
               "filter": [
                   {
                       "range": {
                           "picDate": {
                               "gte": "` + startDate + `",
                               "lte": "` + endDate + `"
                           }
                       }
                   },
               ` + comIdsStr + `
                   {
                       "term": {
                           "documentNumber": "` + docNumber + `"
                       }
                   }
               ]
           }
       },
       "aggs": {
           "group_by_documentnumber": {
               "terms": {
                   "field": "documentNumber",
                   "size": 100000
               },
               "aggs": {
                   "group_by_date": {
                       "date_histogram": {
                           "field": "picDate",
                           "interval": "1d", // 按天分桶
                           "format": "yyyy-MM-dd"
                   "group_by_cameraId": {
                       "terms": {
                           "field": "cameraId",
                           "size": 10000
                       },
                       "aggs": {
                           "top_hits": {
                               "top_hits": {
                                   "_source": [
                                       "id",
                                       "cameraId",
                                       "picDate"
                                   ],
                                   "size": 100000,
                                   "size": 10000,
                                   "sort": [
                                       {
                                           "picDate": {
                                               "order": "desc"
                                               "order": "asc"
                                           }
                                       }
                                   ]
@@ -150,10 +696,50 @@
   if err != nil {
      return nil, err
   }
   result, _ := decodeDocumentInfos(source)
   docResult, err := decodeInfo(intervalInMinutes, source)
   if err != nil {
      return nil, err
   }
   //fmt.Println(docResult)
   result, err := findAnalyzeCoordinatedMovementsInfos(docResult, beforeTime, afterTime, frequency, indexName, serverIp, serverPort)
   if err != nil {
      return nil, err
   }
   //fmt.Println(result)
   return result, nil
}
   return activityId, 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************************************//
@@ -1814,6 +2400,38 @@
}
// 按日期范围,服务器Id删除数据
func DeleteByDocumentNumber(docNumber []string, serverIp string, serverPort string, indexName string) (total int, err error) {
   url := "http://" + serverIp + ":" + serverPort + "/" + indexName + "/_delete_by_query"
   docNumbers := strings.Replace(strings.Trim(fmt.Sprint(docNumber), "[]"), " ", "\",\"", -1)
   deleteJson := `{
   "query":{
      "bool":{
         "filter":[
         {
            "terms":{
               "documentNumber":["` + docNumbers + `"]
            }
         }
         ]
      }
   }
}   `
   //fmt.Println(url)
   //fmt.Println(deleteJson)
   //return
   buf, err := EsReq("POST", url, []byte(deleteJson))
   if err != nil {
      return -1, errors.New("请求失败")
   }
   deleteRes, err := SourceDeleted(buf)
   if err != nil {
      return -1, errors.New("解码失败")
   }
   return deleteRes, nil
}
// 按日期范围,服务器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 := `{