Spring - MonoDB 와 LBS

36967 단어 springmongodbLBS
MongoDB 는 2 차원 공간 인덱스 를 지원 하 며, 공간 인덱스 를 사용 해 지리 적 위 치 를 검색 할 수 있다.
전제조건: 공간 색인 을 만 드 는 key 는 array 나 내장 문 서 를 사용 하여 저장 할 수 있 지만 앞의 두 elements 는 고정된 공간 위치 수 치 를 저장 해 야 합 니 다.... 와 같다
{ loc : [ 50 , 30 ] }
{ loc : { x : 50 , y : 30 } }
{ loc : { foo : 50 , y : 30 } }
{ loc : { lat : 40.739037, long: 73.992964 } }

색인 도 만들어 야 합 니 다:
db.mapinfo.ensureIndex({"loc" : "2d"},{"background" : true})

색인 생 성 여부 보기:
db.mapinfo.getIndexes()

테스트 조회:
db.mapinfo.find({loc : {$near : [72,82]},"category" : "coffee"})

Spring 통합 MongoDB:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    default-autowire="byName">
    <context:property-placeholder location="classpath*:mongodb.properties"/>
                   
    <!--mongodb-->
    <mongo:mongo host="${mongodb.host}" port="${mongodb.port}" >
        <mongo:options connections-per-host="${mongodb.connectionPperHost}"
            threads-allowed-to-block-for-connection-multiplier="${mongodb.threadsAllowedToBlockForConnectionMmultiplier}"
            connect-timeout="${mongodb.connectTimeout}" max-wait-time="${mongodb.connectTimeout}" auto-connect-retry="${mongodb.autoConnectRetry}"
            socket-keep-alive="${mongodb.socketKeepAlive}" socket-timeout="${mongodb.socketTimeout}" slave-ok="${mongodb.slaveOk}"
            write-number="${mongodb.writeNumber}" write-timeout="${mongodb.writeTimeout}" write-fsync="${mongodb.writeFsync}" />
    </mongo:mongo>
    <mongo:db-factory mongo-ref="mongo" dbname="${mongodb.dbname}" username="${mongodb.username}" password="${mongodb.password}"
        id="mongoDbFactory" write-concern="SAFE" />
    <bean id="mappingContext"
        class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
    <bean id="defaultMongoTypeMapper"
        class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
        <constructor-arg name="typeKey">
            <null />
        </constructor-arg>
    </bean>
    <bean id="mappingMongoConverter"
        class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mappingContext" ref="mappingContext" />
        <property name="typeMapper" ref="defaultMongoTypeMapper" />
    </bean>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
        <property name="writeResultChecking" value="EXCEPTION" />
    </bean>
</beans>

속성 파일: mongodb. properties
mongodb.host=127.0.0.1
mongodb.port=27017
mongodb.dbname=mzsx
mongodb.collect=parent
mongodb.username=mzsx
mongodb.password=mzsx
mongodb.connectionPperHost=10
mongodb.threadsAllowedToBlockForConnectionMmultiplier=4
mongodb.connectTimeout=5000
mongodb.maxWaitTime=5000
mongodb.autoConnectRetry=true
mongodb.socketKeepAlive=true
mongodb.socketTimeout=500000
mongodb.slaveOk=true
mongodb.writeNumber=10
mongodb.writeTimeout=0
mongodb.writeFsync=true
mongodb.connections=22
mongodb.connectionThreads=22
mongodb.connectionsPerHost=10
mongodb.threadsMultiplier=4

자바 배경 코드:
package com.digitalchina.lbs.mongo.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.DefaultIndexOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.Box;
import org.springframework.data.mongodb.core.geo.Circle;
import org.springframework.data.mongodb.core.geo.Point;
import org.springframework.data.mongodb.core.geo.Polygon;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.Index.Duplicates;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import com.digitalchina.lbs.mongo.api.MongoLBSAPI;
import com.digitalchina.lbs.serve.util.Distance;
import com.digitalchina.lbs.serve.util.InformationVo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import edu.emory.mathcs.backport.java.util.Collections;
@Component
public class MongoLBSImpl implements MongoLBSAPI {
    private final static Logger log=Logger.getLogger(MongoLBSImpl.class);
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     *  :                     
     *
     * @param lowerLeft           ,upperRight           ,classzz       ,radius    ,key     
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> boxByPage(String collectionName,Query query ,double[] lowerLeft,double[] upperRight,  Class classzz, int startNum,int limit) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   boxByPage() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                log.warn("  MongoLBSImpl   boxByPage() query null。");
                query = new Query();
            }
            //    
            Box box = new Box(lowerLeft, upperRight);
            query.addCriteria(Criteria.where("infoMap.loc").within(box));
            /*if(key!=null){
                query.addCriteria(Criteria.where("infoMap.sname").regex("^.*" + key + ".*$"));
            }*/
            query.skip(startNum);
            query.limit(limit);
            return mongoTemplate.find(query, classzz,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   boxByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :                     
     *
     * @param lowerLeft         ,upperRight         ,classzz       ,radius    ,key     
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> boxByPage(String collectionName,Query query ,Point lowerLeft, Point upperRight, Class classzz, int startNum, int limit) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   boxByPage() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                log.warn("  MongoLBSImpl   boxByPage() query null。");
                query = new Query();
            }
            //  
            Box box = new Box(lowerLeft, upperRight);
            query.addCriteria(Criteria.where("infoMap.loc").within(box));
            /*if(key!=null){
                query.addCriteria(Criteria.where("infoMap.sname").regex("^.*" + key + ".*$"));
            }*/
            query.skip(startNum);
            query.limit(limit);
              
            return mongoTemplate.find(query, classzz,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   boxByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
    //   ,  ,  
    /**
     *  :                       
     *
     * @param centerX       ,centerY       ,classzz       ,radius    ,key     
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> circleByPage(String collectionName,Query query ,double centerX, double centerY,double radius,Class classzz, int startNum, int limit) {
        System.out.println("============MongoLBSImpl=======circleCriteria===========");
        if (collectionName==null) {
            log.error("  MongoLBSImpl   boxByPage() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                log.warn("  MongoLBSImpl   circleByPage() query null。");
                query = new Query();
            }
            //  
            Circle cri = new Circle(centerX, centerY, Distance.getChange(radius));
            query.addCriteria(Criteria.where("infoMap.loc").within(cri));
            query.skip(startNum);
            query.limit(limit);
            //System.out.println("-=-==---=-=--=-=-=-=-========-====:"+query);
            //System.out.println(mongoTemplate.find(query, classzz,collectionName));
            List<InformationVo> list=mongoTemplate.find(query, classzz,collectionName);
            if (list!=null) {
                log.info("  MongoLBSImpl   circleByPage()    。");
                for (InformationVo informationVo : list) {
                    informationVo.setDistance(Distance.GetDistance(centerX, centerY, ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1)));
                }
                Collections.sort(list);
            }
              
            return list;
              
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   circleByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
    /**
     *  :                       
     *
     * @param centerX       ,centerY       ,classzz       ,radius    ,key     
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> circleByPage(String collectionName,Query query ,Point center,double radius,Class classzz, int startNum, int limit){
        if (collectionName==null) {
            log.error("  MongoLBSImpl   boxByPage() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                log.warn("  MongoLBSImpl   circleByPage() query null。");
                query = new Query();
            }
            //  
            Circle cri = new Circle(center, Distance.getChange(radius));
            query.addCriteria(Criteria.where("infoMap.loc").within(cri));
            query.skip(startNum);
            query.limit(limit);
            List<InformationVo> list=mongoTemplate.find(query, classzz,collectionName);
            if (list!=null) {
                log.info("  MongoLBSImpl   circleByPage()    。");
                for (InformationVo informationVo : list) {
                    informationVo.setDistance(Distance.GetDistance(center.getX(), center.getY(), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1)));
                }
                  
            }
            Collections.sort(list);
            return list;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   circleByPage()    。");
            e.printStackTrace();
            return null;
        }
          
    }
      
    //     ,   
    /**
     *  :                 
     *
     * @param startNum     ,limit    ,criteria       
     *@return List<InformationVo>
     * **/
    public List<InformationVo> conditionByPage(String collectionName,int startNum, int limit,Criteria... criteria) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   conditionByPage() collectionName null");
            return null;
        }
        try {
            //   
            Query query = new Query();
            query.skip(startNum);
            query.limit(limit);
            for (Criteria c : criteria) {
                query.addCriteria(c);
            }
            return mongoTemplate.find(query, InformationVo.class,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   conditionByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :                 
     *
     * @param startNum     ,limit    ,query       
     *@return List<InformationVo>
     * **/
    public List<InformationVo> conditionByPage(String collectionName,int startNum, int limit,Query query) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   boxByPage() collectionName null");
            return null;
        }
        try {
            //   
            if (query==null) {
                query = new Query();
            }
            query.skip(startNum);
            query.limit(limit);
            /*for (Criteria c : criteria) {
                query.addCriteria(c);
            }*/
            return mongoTemplate.find(query, InformationVo.class,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   conditionByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :         
     *
     * @param collectionName         ;collectionOptions         (CollectionOptions(Integer size, Integer maxDocuments, Boolean capped),size            byte,maxDocuments       ,capped         )
     *@return boolean
     * **/
    public boolean createCollection(String collectionName,
            CollectionOptions collectionOptions) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   createCollection() collectionName null");
            return false;
        }
        try {
            if (collectionOptions!=null) {
                log.info("  createCollection("+collectionName+","+collectionOptions+");");
                mongoTemplate.createCollection(collectionName, collectionOptions);
            }else{
                log.info("  createCollection("+collectionName+");");
                mongoTemplate.createCollection(collectionName);
            }
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   createCollection()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    //    --   
    public boolean createdGeoIndex(String collectionName, String indexName,
            String key, Integer max, Integer min) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   createdGeoIndex() collectionName null");
            return false;
        }
        try {
            System.out.println("===========createdGeoIndex=============");
            DefaultIndexOperations indexopera=new DefaultIndexOperations(mongoTemplate, collectionName);
            GeospatialIndex geoIndex=new GeospatialIndex(key) ;
            if(indexName!=null){
                geoIndex.named(indexName);
            }
            if ( max!= null) {
                geoIndex.withMax(max);
            }else {
                geoIndex.withMax(180);
            }
            if ( min!= null) {
                geoIndex.withMax(min);
            }else {
                geoIndex.withMax(-180);
            }
              
            indexopera.ensureIndex(geoIndex);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   createdGeoIndex()    。");
            e.printStackTrace();
            return false;
        }
    }
    /**
     *  :               
     *
     * @param collectionName       ;indexName         ;key         ;
     * duplicates         ,    null   Index.Duplicates.RETAIN (  ),    Index.Duplicates.DROP(  );order        ,    
     *@return boolean
     * **/
    public boolean createdIndex(String collectionName, String indexName,
            String key, Duplicates duplicates, Order order) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   createdIndex() collectionName null");
            return false;
        }
          
        try {
            DefaultIndexOperations indexopera=new DefaultIndexOperations(mongoTemplate, collectionName);
            Index index=new Index(key, order) ;
            index.named(indexName);
            if (duplicates!=null) {
                index.unique(duplicates);
            }
            indexopera.ensureIndex(index);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   createdIndex()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *  :            
     *
     * @param collectionName       
     *@return boolean
     * **/
    public boolean dropAllIndexeByALL(String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   dropAllIndexeByALL() collectionName null");
            return false;
        }
        try {
            DefaultIndexOperations index=new DefaultIndexOperations(mongoTemplate, collectionName);
            index.dropAllIndexes();
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   dropAllIndexeByALL()    。");
            e.printStackTrace();
            return false;
        }
    }
      
      
    /**
     *  :         
     *
     * @param collectionName         ;collectionOptions         (CollectionOptions(Integer size, Integer maxDocuments, Boolean capped),size            byte,maxDocuments       ,capped         )
     *@return boolean
     * **/
    public boolean dropCollection(String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   dropCollection() collectionName null");
            return false;
        }
        try {
            mongoTemplate.dropCollection(collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   dropCollection()    。");
            e.printStackTrace();
            return false;
        }
    }
      
      
    /**
     *  :       
     *
     * @param collectionName       ;indexName         ;
     *@return boolean
     * **/
    public boolean dropIndex(String collectionName, String indexName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   dropIndex() collectionName null");
            return false;
        }
        try {
            DefaultIndexOperations index=new DefaultIndexOperations(mongoTemplate, collectionName);
            index.dropIndex(indexName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   dropIndex()    。");
            e.printStackTrace();
            return false;
        }
    }
    /**
     *  :                  
     *
     * @param  
     *@return DBCollection
     * **/
    public  boolean collectionExists(String collectionName){
        if (collectionName==null) {
            log.error("  MongoLBSImpl   collectionExists() collectionName null");
            return false;
        }
        try {
            return mongoTemplate.collectionExists(collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   collectionExists()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *  :           
     *
     * @param classzz       
     *            (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> findAll(String collectionName,Class classzz) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   findAll() collectionName null");
            return null;
        }
        try {
            return mongoTemplate.find(new Query(), classzz, collectionName);
            //return mongoTemplate.findAll(classzz, classzz.getName());// find(new
                                                                        // Query(),InformationVo.class);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   findAll()    。");
            e.printStackTrace();
            return null;
        }
    }
    /**
     *  :             
     *
     * @param classzz       
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> findAllByPage(String collectionName,Class classzz, int startNum,
            int limit) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   findAllByPage() collectionName null");
            return null;
        }
        try {
            //   
            Query query = new Query();
            query.skip(startNum);
            query.limit(limit);
            return mongoTemplate.find(query, classzz,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   findAllByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :               
     *
     * @param criteria       ,criteria       
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public InformationVo findOne(String collectionName,Criteria criteria, Class classzz) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   findOne() collectionName null");
            return null;
        }
        try {
            //   
            Query query = new Query();
            query.addCriteria(criteria);
            query.limit(1);
            List<InformationVo> list=mongoTemplate.find(query, classzz,collectionName);
            if (list.size()>0) {
                return list.get(0);
            }else {
                return null;
            }
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   findOne()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :              
     *
     * @param  
     *@return DBCollection
     * **/
    public DBCollection getCollection(String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   getCollection() collectionName null");
            return null;
        }
        try {
            return mongoTemplate.getCollection(collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   getCollection()    。");
            e.printStackTrace();
            return null;
        }
          
    }
      
    /**
     *  :            
     *
     * @param query      ;collectionName     
     *@return long(   -1.    )
     * **/
    public long getCount(Query query, String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   getCount() collectionName null");
            return -1;
        }
        try {
            return mongoTemplate.count(query, collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   getCount()    。");
            e.printStackTrace();
            return -1;
        }
          
    }
      
    /**
     *  :       
     *
     * @param  
     *@return DB
     * **/
    public DB getDb() {
        try {
            return mongoTemplate.getDb();
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   getDb()    。");
            e.printStackTrace();
            return null;
        }
          
    }
      
    /**
     *   :          
     *
     * @param list      
     *            ,classzz       (  )
     * @return boolean
     * **/
    //@SuppressWarnings("unchecked")
    public boolean insertList(List<? extends Object> list, String collectionName) {
        try {
            mongoTemplate.insert(list, collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   insertList()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *   :          
     *
     * @param obj    
     *            (  )
     * @return boolean
     * **/
    public boolean insertObject(Object obj,String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   insertObject() collectionName null");
            return false;
        }
        try {
            mongoTemplate.insert(obj, collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   insertObject()    。");
            e.printStackTrace();
            return false;
        }
    }
    /**
     *  :                        
     *
     * @param point    ;classzz       ;maxDistance           ;key     
     *            ,startNum     ,limit    
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> nearMaxDistance(String collectionName,Point point, Query query,
            Class classzz, Double maxDistance, int startNum, int limit) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   nearMaxDistance() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                query = new Query();
            }
            System.out.println("======MongoLBSImpl+++====="+maxDistance);
            if (maxDistance==null) {
                query.addCriteria(Criteria.where("infoMap.loc").near(point));
            }else {
                query.addCriteria(Criteria.where("infoMap.loc").near(point).maxDistance(Distance.getChange(maxDistance)));
            }
            //query.addCriteria(Criteria.where("infoMap.loc").near(point).maxDistance(maxDistance));
            /*if(key!=null){
                query.addCriteria(Criteria.where("infoMap.sname").regex("^.*" + key + ".*$"));
            }*/
            query.skip(startNum);
            query.limit(limit);
            List<InformationVo> list=mongoTemplate.find(query, classzz,collectionName);
            if (list!=null) {
                for (InformationVo informationVo : list) {
                    //Double double1=Distance.GetDistance(point.getX(), point.getY(), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1));
                    informationVo.setDistance(Distance.GetDistance(point.getX(), point.getY(), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1)));
                    //System.out.println("MongoLBSImpl=====  :"+double1);
                    //System.out.println("+++++MongoLBSImpl+++++++++"+point.getX()+"==="+ point.getY()+"==="+ ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0)+"==="+ ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1));
                }
                  
            }
            Collections.sort(list);
            return list;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   nearMaxDistance()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :                        
     *
     * @param lat    ,lnt    ,classzz       ,maxDistance           ,key     
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> nearMaxDistance(String collectionName,double lat, double lnt,
            Query query, Class classzz, Double maxDistance, int startNum,
            int limit) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   nearMaxDistance() collectionName null");
            return null;
        }
        try {
            if (query==null) {
                query = new Query();
            }
            Point point=new Point(lat, lnt);
            if (maxDistance==null) {
                query.addCriteria(Criteria.where("infoMap.loc").near(point));
            }else {
                query.addCriteria(Criteria.where("infoMap.loc").near(point).maxDistance(Distance.getChange(maxDistance)));
            }
            /*if(key!=null){
                query.addCriteria(Criteria.where("infoMap.sname").regex("^.*" + key + ".*$"));
            }*/
            query.skip(startNum);
            query.limit(limit);
            List<InformationVo> list=mongoTemplate.find(query, classzz,collectionName);
            if (list!=null) {
                for (InformationVo informationVo : list) {
                    //Double double1=Distance.GetDistance(point.getX(), point.getY(), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1));
                    informationVo.setDistance(Distance.GetDistance(point.getX(), point.getY(), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0), ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1)));
                    //System.out.println("MongoLBSImpl=====  :"+double1);
                    //System.out.println("+++++MongoLBSImpl+++++++++"+point.getX()+"==="+ point.getY()+"==="+ ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(0)+"==="+ ((List<Double>)(informationVo.getInfoMap().get("loc"))).get(1));
                }
                  
            }
              
              
            Collections.sort(list);
            return list;
              
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   nearMaxDistance()    。");
            e.printStackTrace();
            return null;
        }
    }
      
    /**
     *  :               
     *
     * @param centerX       ,centerY       ,classzz       ,radius    
     *            ,startNum     ,limit    (  )
     *@return List<InformationVo>
     * **/
    @SuppressWarnings("unchecked")
    public List<InformationVo> polygonByPage(String collectionName,Query query ,Class classzz, int startNum,
            int limit, Point x, Point y, Point z, Point... others) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   polygonByPage() collectionName null");
            return null;
        }
        try {
            if(query==null){
                query = new Query();
            }
            //    
            Polygon polygon = new Polygon(x,y,z,others);
            query.addCriteria(Criteria.where("infoMap.loc").within(polygon));
            /*if(key!=null){
                query.addCriteria(Criteria.where("infoMap.sname").regex("^.*" + key + ".*$"));
            }*/
            query.skip(startNum);
            query.limit(limit);
            return mongoTemplate.find(query, classzz,collectionName);
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   polygonByPage()    。");
            e.printStackTrace();
            return null;
        }
    }
    /**
     *  :           
     *
     * @param query      ,update      (  )
     *@return List<InformationVo>
     * **/
    public boolean remove(Query query,String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   remove() collectionName null");
            return false;
        }
        try {
            mongoTemplate.remove(query,collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   remove()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *  :             
     *
     * @param collectionName       
     *@return boolean
     * **/
    public boolean resetIndexCache(String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   resetIndexCache() collectionName null");
            return false;
        }
        try {
            DefaultIndexOperations index=new DefaultIndexOperations(mongoTemplate, collectionName);
            index.resetIndexCache();
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   resetIndexCache()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *   :          ,       ,     
     *
     * @param obj    
     *            (  )
     * @return boolean
     * **/
    public boolean saveObject(Object obj, String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   resetIndexCache() collectionName null");
            return false;
        }
        try {
            if (obj==null) {
                return false;
            }
            mongoTemplate.save(obj,collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   resetIndexCache()    。");
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *  :    
     *
     * @param query      ,update      (  )
     *@return List<InformationVo>
     * **/
    public boolean updateFirst(Query query, Update update,String collectionName) {
        if (collectionName==null) {
            log.error("  MongoLBSImpl   resetIndexCache() collectionName null");
            return false;
        }
        try {
            mongoTemplate.updateFirst(query, update, collectionName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
      
    /**
     *  :    
     *
     * @param query      ,update      (  )
     *@return List<InformationVo>
     * **/
    public boolean updateMulti(Query query, Update update,String collectionName) {
        if (collectionName==null) {
            return false;
        }
        try {
            mongoTemplate.updateMulti(query, update, collectionName);
            return true;
        } catch (Exception e) {
            log.warn("  MongoLBSImpl   resetIndexCache()    。");
            e.printStackTrace();
            return false;
        }
    }
      
      
}

좋은 웹페이지 즐겨찾기