当前位置: 首页 > 知识库问答 >
问题:

spring数据mongodb中的二维球体索引

徐奇
2023-03-14

我正在处理mongodb的地理空间查询,我在mongo控制台上执行了以下查询

db.items.find(
   {
     location:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [77.026638, 28.459497 ] },
            $maxDistance: 10000
          }
       }
   }
)

但是如何使用spring数据mongodb标准编写此查询?

我尝试使用以下标准,但不起作用

 Criteria criteria = Criteria.where("location").near(new Point(77.026638, 28.459497)).maxDistance(1000);

        Query query = new Query(criteria);
System.out.println(mongoTemplate.find(query, Item.class));

堆栈跟踪

org.springframework.data.mongodb.UncategorizedMongoDbException: Unable to execute query: error processing query: ns=geolocation.items limit=0 skip=0
Tree: GEONEAR  field=location maxdist=1.79769e+308 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query; nested exception is com.mongodb.MongoException: Unable to execute query: error processing query: ns=geolocation.items limit=0 skip=0
Tree: GEONEAR  field=location maxdist=1.79769e+308 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query
    at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:90)
    at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:1940)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1823)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1633)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1616)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:535)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:526)
    at com.samepinch.dao.item.ItemDao$$EPWN0nhQ.getItemsByLocation(ItemDao.java:200)
    at com.samepinch.dao.item.ItemDao$$DPWN0nhQ.getItemsByLocation(Unknown Source)
    at com.samepinch.dao.item.ItemDao.getItemsByLocation(ItemDao.java)
    at com.samepinch.services.item.ItemService.getItemsByLocation(ItemService.java:410)
    at com.samepinch.controllers.item.ItemController.getItemsbyLocation(ItemController.java:222)
    at com.samepinch.controllers.item.ItemController$$FastClassBySpringCGLIB$$33bec54c.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at com.samepinch.controllers.item.ItemController$$EnhancerBySpringCGLIB$$7fa26c49.getItemsbyLocation(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1299)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at com.samepinch.mongodb.springsecurity.filters.AuthenticationFilter.doFilter(AuthenticationFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mongodb.MongoException: Unable to execute query: error processing query: ns=geolocation.items limit=0 skip=0
Tree: GEONEAR  field=location maxdist=1.79769e+308 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query
    at com.mongodb.QueryResultIterator.throwOnQueryFailure(QueryResultIterator.java:214)
    at com.mongodb.QueryResultIterator.init(QueryResultIterator.java:198)
    at com.mongodb.QueryResultIterator.initFromQueryResponse(QueryResultIterator.java:176)
    at com.mongodb.QueryResultIterator.<init>(QueryResultIterator.java:64)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:86)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
    at com.mongodb.DBCursor._check(DBCursor.java:458)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:546)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:571)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1809)
    ... 105 more

我的架构是

@Document(collection = "items")
public class Item extends BaseEntity{
    private static final long serialVersionUID = 1L;

    private String itemName;
    private MetadataEnum categoryName;
    private List<SubtypeEnum> attributes;
    private String registerBy;
    boolean isAccessed;
    private String imageUrl;
    private CatagoryPreference catagoryPreference;
    private Date startDate,endDate; 

    private Location location;
}

嵌入的文档为:)

public class Location {

    private List<Double> coordinates;
    private String type;
    public List<Double> getCoordinates() {
        return coordinates;
    }
    public void setCoordinates(List<Double> coordinates) {
        this.coordinates = coordinates;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    public Double getRadius() {
        return radius;
    }
    public void setRadius(Double radius) {
        this.radius = radius;
    }

    private Double radius;

}

即使我找到系统索引确保

{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.notification" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.preference" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.userItemHistory" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.media" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.userBasedRecommendation" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.users" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.authenticationToken" }
{ "v" : 1, "unique" : true, "key" : { "username" : 1 }, "name" : "username", "ns" : "geolocation.users" }
{ "v" : 1, "unique" : true, "key" : { "email" : 1 }, "name" : "email", "ns" : "geolocation.users" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.userToUserHistory" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.metadata" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.mongo_data_model_map" }
{ "v" : 1, "key" : { "element_id" : 1 }, "name" : "element_id_1", "ns" : "geolocation.mongo_data_model_map" }
{ "v" : 1, "key" : { "long_value" : 1 }, "name" : "long_value_1", "ns" : "geolocation.mongo_data_model_map" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.preferenceOrder" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.counter" }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.item" }
{ "v" : 1, "key" : { "location" : "2dsphere" }, "name" : "location_2dsphere", "ns" : "geolocation.item", "2dsphereIndexVersion" : 2 }
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "geolocation.items" }
{ "v" : 1, "key" : { "location" : "2dsphere" }, "name" : "location_2dsphere", "ns" : "geolocation.items", "2dsphereIndexVersion" : 2 }
Type "it" for more
> it
{ "v" : 1, "key" : { "a" : 1 }, "name" : "a_1", "ns" : "geolocation.items" }

我的数据库记录看起来像

{
    "_id" : NumberLong(46602),
    "_class" : "com.samepinch.domain.item.Item",
    "itemName" : "Chandigarh",
    "categoryName" : "TRAVELLING",
    "attributes" : [
        "MOUNTAIN"
    ],
    "isAccessed" : false,
    "imageUrl" : "0bbd8cdb-be5c-4efc-b974-c04fb1903537itemcompressed.jpg",
    "catagoryPreference" : "BOTH",
    "startDate" : ISODate("2015-12-09T18:30:00Z"),
    "endDate" : ISODate("2015-12-09T18:30:00Z"),
    "location" : {
        "coordinates" : [
            76.76641440000003,
            30.72642125251779
        ],
        "type" : "Point",
        "radius" : 8504.948210235696
    },
    "createdDate" : ISODate("2015-12-09T10:27:42.519Z"),
    "updatedDate" : ISODate("2015-12-09T10:27:42.519Z")
}

我在集合上创建了2d spheare索引,但我不知道为什么它会给我这个错误。

共有2个答案

微生耘豪
2023-03-14

甚至我也面临这个问题。经过这么多努力,我在没有使用Criteria的情况下找到了它。下面这个是使用不使用Spring...即只有java这绝对会帮助你

    MongoClient mongoClient = new MongoClient("localhost" , 27017 );
    DB db = mongoClient.getDB("services");
    DBCollection collection=  db.getCollection("timezone");
    BasicDBObject point = new BasicDBObject("type", "Point");
    double[] ptCordinate={lat,longi};
    point.put("coordinates", ptCordinate);

    BasicDBObject query = new BasicDBObject(
        "geometry", new BasicDBObject(
            "$near", new BasicDBObject(
                "$geometry", point
            )
        )
    );
    collection.findOne(query);
邴星洲
2023-03-14

更改数据存储而不是:

"location" : {
    "coordinates" : [
        76.76641440000003,
        30.72642125251779
    ],
    "type" : "Point",
    "radius" : 8504.948210235696
}

"location" : {
    "coordinates" : [
        76.76641440000003,
        30.72642125251779
    ],
    "type" : "Point"
}

我认为对于“点”类型,您的数据类型是错误的。它应该只有经度和纬度作为地理坐标。您不应包括“RADUI”。

检查有效的Geojson。

 类似资料:
  • 问题内容: 假设我有一张带有行星圆柱图的图像,比如说: http://www.johnstonsarchive.net/spaceart/cymaps.html 我想把它画在一个三维球体上,以恢复物体的原始形状 行星。 有没有一种方法可以使用像matplotlib,mayavi, 底图还是类似的? 问题答案: 更新:这是使用Cartopy的新版本,如[basemap is] [下线](https:

  • 我正在尝试使用查询搜索出生日期 我如何才能搜索dob在等位日期格式?

  • 我正在尝试按日期使用过滤器,如下所示。 但与使用ISO格式“2015-05-16T07:55:23.257Z”不同,spring数据mongodb生成以下查询

  • 我开发了一个程序,获取包含用户id及其技能的用户技能数组,该数组如下: 关键是user_id,值是技能数组,现在我想搜索有两个值的user_id:english或word,我希望返回17,16,我该怎么做,谢谢你的帮助:)

  • 我有一个疑问。有没有一种有效的方法来求一个numpy矩阵的所有邻域的和而不使用几个条件? 这是一个例子: 当我运行时,它返回我3,而不是一个错误,因此如果我想将1添加到一个值的所有邻居中,我需要使用很多条件,因为我不能只使用,因为在这种情况下以及在其他情况下,它只返回我一个“假邻居”

  • 我有以下数据模型 和spring数据存储库接口 但findByIdIn方法返回一个空列表,即使mongodb中存在ID。我已经为文档中的其他字段测试了findbyxxin(),它们都工作得很好。但当涉及到文档id时,情况并非如此。 这是我第一次使用mongoDB,但我熟悉Spring data jpa。 我知道 但我还需要对结果应用分页,因此对我的情况没有帮助。 我尝试使用@Query(带有in查