Bläddra i källkod

feat:mongo聚合查询测试

wangweiyu 4 år sedan
förälder
incheckning
1310c646e2

+ 11 - 0
src/main/java/com/aoyang/tms/controller/TestController.java

@@ -22,7 +22,9 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import java.time.LocalDateTime;
+import java.util.Arrays;
 import java.util.List;
+import java.util.stream.Collectors;
 
 /**
  * @Description: 作业人员相关接口
@@ -190,5 +192,14 @@ public class TestController {
         Result<Boolean> send = messageFeign.send(smsSend, null, null, null);
         return send;
     }
+    @ApiOperation(value = "测试运单短信模板", notes = "根据经纬度查询位置")
+    @PostMapping("/test_mongo_group")
+    public Result testGroup(@RequestParam String truckIds) {
+        String[] split = truckIds.split(",");
+        List<String> list = Arrays.asList(split);
+        List<Long> ids = list.stream().
+                map(s->Long.parseLong(s)).collect(Collectors.toList());
+        return new Result(commonService.getLocation(ids));
+    }
 
 }

+ 8 - 0
src/main/java/com/aoyang/tms/service/CommonService.java

@@ -10,6 +10,8 @@ import com.aoyang.tms.feign.result.Org;
 
 import java.time.LocalDateTime;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 /**
  * @Description: 常用工具类,如获取组织信息、用户信息、卡车信息、验证Result、验证通联返回值
@@ -128,6 +130,12 @@ public interface CommonService {
 
 
     /**
+     * 根据truckId获取车辆信息
+     */
+    Map<Long, LocationVO> getLocation(List<Long> truckId);
+
+
+    /**
      * 根据时间根据truckId获取车辆信息
      */
     LocationVO getLocationByDate(Long truckId, LocalDateTime date);

+ 85 - 3
src/main/java/com/aoyang/tms/service/impl/CommonServiceImpl.java

@@ -26,6 +26,7 @@ import org.apache.http.util.EntityUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.mongodb.core.MongoTemplate;
+import org.springframework.data.mongodb.core.aggregation.*;
 import org.springframework.data.mongodb.core.query.Criteria;
 import org.springframework.data.mongodb.core.query.Query;
 import org.springframework.stereotype.Service;
@@ -33,9 +34,7 @@ import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 import java.io.IOException;
 import java.time.LocalDateTime;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
 
 /**
  * @Description: 公共类,方便服务间调用
@@ -358,6 +357,89 @@ public class CommonServiceImpl implements CommonService {
     }
 
     @Override
+    public Map<Long, LocationVO> getLocation(List<Long> truckIds) {
+        List<String> clientIds = new ArrayList();
+        for (Long truckId : truckIds) {
+            QueryWrapper<TruckSimCard> queryWrapper = new QueryWrapper<>();
+            queryWrapper.eq("truck_id", truckId);
+            TruckSimCard truckSimCard = truckSimCardService.getOne(queryWrapper);
+            if (truckSimCard == null) {
+                log.error("绑定信息不存在 truckId:{}", truckId);
+                clientIds.add(null);
+                continue;
+            }
+            clientIds.add(truckSimCard.getClientId());
+        }
+        log.info("getLocation clientIds:{}", JSON.toJSONString(clientIds));
+        Query query = new Query(Criteria.where("clientId").in(clientIds).and("messageId").is(512));
+        query.with(new Sort(Sort.Direction.DESC, "dateTime"));
+
+//        // 聚合操作
+//        List<AggregationOperation> operations = new ArrayList<>();
+//        // 筛选条件
+//        operations.add(Aggregation.match(Criteria.where("clientId").in(clientIds).and("messageId").is(512)));
+//        operations.sort(new Sort(Sort.Direction.DESC, "dateTime"));
+//
+//        // 分组字段
+//        GroupOperation groupOperation = Aggregation.group("clientId").first();
+//        SortOperation sortOperation = Aggregation.sort(Sort.by(Sort.Direction.DESC, "dateTime"));
+//        // 聚合查询字段
+////        for (int i = 0; i < queryKey.length; i++) {
+////            groupOperation = groupOperation.sum(queryKey[i]).as(queryKey[i]);
+////        }
+//        // 添加选项  (聚合查询字段和添加筛选是有区别的注意)
+//        operations.add(groupOperation);
+//        operations.add(sortOperation);
+//
+//        // 最终聚合查询所有信息
+//        Aggregation aggregation = Aggregation.newAggregation(operations);
+//
+//        // 查询结果
+//        AggregationResults<HashMap> results = mongoTemplate.aggregate(aggregation, "tms_dev", HashMap.class);
+//        //获取结果
+//        List<HashMap> result = results.getMappedResults();
+
+        TypedAggregation typedAggregation = TypedAggregation.newAggregation(TmsMongoDoc.class,
+                Arrays.asList(
+                        //筛选过滤条件
+                        TypedAggregation.match(Criteria.where("clientId").in(clientIds).and("messageId").is(512)),
+                        //分组过滤条件,sort的顺序有要求,在分组方法前就是先排序后分组
+                        TypedAggregation.sort(Sort.by(Sort.Direction.DESC, "dateTime")),
+                        TypedAggregation.group("clientId")
+                                .first("latitude").as("latitude")
+                                .first("longitude").as("longitude")
+                                .first("createTime").as("createTime")
+                                .first("clientId").as("clientId")
+                ));
+
+        List<TmsMongoDoc> tmsMongoDocs =
+                mongoTemplate.aggregate(typedAggregation, TmsMongoDoc.class).getMappedResults();
+//        if (tmsMongoDoc != null) {
+//            location = new LocationVO();
+//            location.setLatitude(tmsMongoDoc.getLatitude() + "");
+//            location.setLongitude(tmsMongoDoc.getLongitude() + "");
+//            location.setCarNumber(truckSimCard.getCarNumber());
+//            location.setTruckId(truckSimCard.getTruckId());
+//            location.setDate(tmsMongoDoc.getCreateTime());
+//        }
+//        return location;
+        log.info("getLocation results:{}", JSON.toJSONString(tmsMongoDocs));
+        Map<Long, LocationVO> result = new HashMap();
+        for (TmsMongoDoc doc : tmsMongoDocs) {
+            for (int i=0;i<clientIds.size();i++) {
+                if (clientIds.get(i).equals(doc.getClientId())) {
+                    LocationVO location = new LocationVO();
+                    location.setLatitude(doc.getLatitude() + "");
+                    location.setLongitude(doc.getLongitude() + "");
+                    location.setDate(doc.getCreateTime());
+                    result.put(truckIds.get(i), location);
+                }
+            }
+        }
+        return result;
+    }
+
+    @Override
     public LocationVO getLocationByDate(Long truckId, LocalDateTime date) {
         LocationVO location = null;
         QueryWrapper<TruckSimCard> queryWrapper = new QueryWrapper<>();